我正在使用OneWayToSource绑定,它似乎总是将我的源属性设置为空。为什么呢?这给我带来了麻烦,因为我需要源属性中目标属性的值而不是空值。
这是我的代码:
MyViewModel.cs:
public class MyViewModel
{
    private string str;
    public string Txt
    {
        get { return this.str; }
        set { this.str = value; }
    }
}
主窗口.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>
我的按钮.cs:
public class MyButton : Button
{
    public MyButton()
    {
        this.Content = "765";
    }
}
目标属性是MyButton.Content。源属性是MyViewModel.Txt。该Txt属性应设置为“765”,但它为空。
为什么我收到 null 而不是 765?
编辑:
请查看MyButton构造函数内部。实际上,如果您使用简单TwoWay,它将起作用。我对其进行了测试,它与在构造函数中设置的内容无关。我猜它是有OneWayToSource约束力的。
现在来解释我是如何使用TwoWay绑定的,我确实通过调用方法在构造函数中设置了 dp 的值,setvalue但是在包装器内部,或者更好地说是 getter 和 setter,我没有提供任何 setter,因此为什么我让我TwoWay看起来像它的OneWayToSource. 我这样做是为了测试它的构造函数是否出错。我认为 viewmodel 中的属性的值为 765,所以这就是TwoWay绑定的意思。我只是测试了它是否是控制构造函数。在构造函数中设置一个值就可以了。
通过隐藏 setter 我的意思是这个 set {}