如何将文本框的文本双向数据绑定到依赖项 属性

How to Two-way databind a TextBox's Text to a Dependency property

我正在尝试双向数据绑定文本框的文本 属性 到父 window 的依赖项 属性。

我已将问题缩减为测试项目中的几行代码以尝试使绑定​​正常工作,并且已经谷歌搜索了好几天。

来自 Xaml 文件:

<StackPanel>
    <TextBox Text="{Binding A, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Mode=TwoWay}" Margin="5"/>
    <TextBox Text="{Binding B, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Mode=TwoWay}" Margin="5"/>
    <Button Content="Random" Click="Button_Click" Margin="5"/>
</StackPanel>

以及来自 CS 文件:

public partial class MainWindow : Window
{
    public static readonly DependencyProperty AProperty = DependencyProperty.Register("A", typeof(double), typeof(MainWindow));
    public double A
    {
        get { return (double)GetValue(AProperty); }
        set
        {
            SetValue(AProperty, value);
            SetValue(BProperty, value);
        }
    }

    public static readonly DependencyProperty BProperty = DependencyProperty.Register("B", typeof(double), typeof(MainWindow));
    public double B
    {
        get { return (double)GetValue(BProperty); }
        set
        {
            SetValue(AProperty, value);
            SetValue(BProperty, value);
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        A = 0d;
        B = 1d;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        A = new Random().Next();
    }
}

当 window 启动时,两个 TextBox 都显示“1”(正如预期的那样,因为构造函数)。单击该按钮会导致两个 TextBox 更新为随机数(也符合预期)。

但是更改任一 TextBox 中的文本不会更新绑定的依赖项 属性,因此它不会更新另一个 TextBox。

这些操作期间没有任何错误消息。

如果您希望 A 设置 B,反之亦然,您应该使用回调。 CLR 包装器的 setter 应该 调用依赖项 属性 本身的 SetValue,不要做任何其他事情,例如:

public static readonly DependencyProperty AProperty = DependencyProperty.Register("A", typeof(double), typeof(MainWindow),
    new PropertyMetadata(new PropertyChangedCallback(OnAChanged)));

public double A
{
    get { return (double)GetValue(AProperty); }
    set { SetValue(AProperty, value); }
}

private static void OnAChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    MainWindow window = (MainWindow)d;
    window.B = window.A;
}

public static readonly DependencyProperty BProperty = DependencyProperty.Register("B", typeof(double), typeof(MainWindow));
public double B
{
    get { return (double)GetValue(BProperty); }
    set { SetValue(BProperty, value); }
}

另请注意,如果您希望为每次击键设置源 属性,则应将绑定的 UpdateSourceTrigger 属性 设置为 PropertyChanged。默认情况下,它们将在 TextBox 失去焦点时设置。