【发布时间】:2013-04-23 04:37:27
【问题描述】:
我正在使用OneWayToSource 绑定,它似乎总是将我的源属性设置为空。为什么呢?这给我带来了麻烦,因为我需要源属性中目标属性的值而不是 null。
这是我的代码:
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";
}
}
目标属性是MyButton.Content。源属性是MyViewModel.Txt。 Txt 属性应设置为“765”,但它为空。
为什么我收到的是 null 而不是 765?
编辑:
请查看MyButton 构造函数的内部。实际上,如果您使用简单的TwoWay,它将起作用。我对其进行了测试,它与在构造函数中设置的内容无关。我猜它与OneWayToSource 绑定有关。
现在解释我是如何使用TwoWay 绑定的,我确实通过调用setvalue 方法在构造函数中设置了dp 的值,但是在包装器内部或者更好地说是getter 和setter,因此我没有提供任何setter为什么我让我的TwoWay 有点像它的OneWayToSource。我这样做是为了测试它的构造函数是否出错。我认为 viewmodel 中的属性的值为 765,所以这就是我对 TwoWay 绑定的意思。我只是测试了它是否是控制构造函数。在构造函数中设置一个值就可以了。
我的意思是隐藏 setter 设置{}
【问题讨论】:
-
你得到任何 BindingErrors 吗?