我正在使用OneWayToSource
绑定,它似乎总是将我的源属性设置为null。为什么?这是我的麻烦,因为我需要源属性中的目标属性的值,而不是null。OneWayToSource窘境
这里是我的代码:
MyViewModel.cs:
public class MyViewModel
{
private string str;
public string Txt
{
get { return this.str; }
set { this.str = value; }
}
}
MainWindow.cs:
public MainWindow()
{
InitializeComponent();
MyViewModel vm = new MyViewModel();
vm.Txt = "123";
this.DataContext = vm;
}
MainWindow.xaml:
个<Window x:Class="OneWayToSourceTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:OneWayToSourceTest">
<Grid>
<local:MyButton Content="{Binding Path=Txt, Mode=OneWayToSource}"/>
</Grid>
</Window>
MyButton.cs:
public class MyButton : Button
{
public MyButton()
{
this.Content = "765";
}
}
target属性是MyButton.Content
。源属性是MyViewModel.Txt
。 Txt
属性应该设置为“765”,但它是空的。
为什么我会收到空值而不是765?
编辑:
请看看里面MyButton
构造。其实如果你会使用简单的TwoWay
它会起作用。我测试了它,它与构造函数中设置的内容无关。它的东西与OneWayToSource
绑定我猜。
我们解释我是如何用TwoWay
绑定,我没有通过调用setvalue
方法,但再包装或更好的内部设置构造函数中的DP值表示getter和setter我没有提供任何二传手因此为什么我做了我的TwoWay
有点像它的OneWayToSource
。我做了它来测试它的构造函数是否有错。我认为viewmodel内的属性值为765,所以这就是我的意思是TwoWay
绑定。我只是测试它是否是控件构造函数。它的一切都很好,在构造函数中设置一个值。
通过隐藏二传手我的意思是 集合{}
您是否收到任何BindingErrors? – Jehof 2013-04-29 13:33:18
不,我不。 : - (( – 2013-04-29 13:33:54