我正在使用OneWayToSource
绑定,但是它似乎总是将我的源属性设置为null。为什么会这样?这给我带来了麻烦,因为我需要从目标属性中获取值到我的源属性而不是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。为什么会收到 null 而不是 765?
编辑:
请查看
MyButton
构造函数内部。实际上,如果您使用简单的TwoWay
,它就能正常工作。我测试了一下,这与在构造函数中设置内容无关。我想这可能与OneWayToSource
绑定有关。现在来解释一下我如何使用
TwoWay
绑定,我通过调用setvalue
方法在构造函数内部设置了dp的值,但是在包装器或者更好地说是getter和setter内部,我没有提供任何setter,因此我的TwoWay
看起来有点像OneWayToSource
。 我这样做是为了测试是否是构造函数的问题。我发现视图模型中的属性具有值765,这就是我所说的TwoWay
绑定。我只是测试是否是控件构造函数的问题。 在构造函数中设置值完全没问题。隐藏setter是指这个 set {} 。