繁体   English   中英

绑定到DependencyProperty没有结果

[英]Binding to DependencyProperty with no result

我有绑定到我的新控件的依赖属性的问题。
我决定写一些测试来检查这个问题。

从TextBox.Text绑定到另一个TextBox.Text

XAML代码:

<TextBox Name="Test" Text="{Binding ElementName=Test2, Path=Text, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Name="Test2" Grid.Row="2" />

结果很好 - 当我在第一个TextBox中写东西时 - >第二个TextBox正在更新(反过来也是)。

在此输入图像描述

我创建了新的控件 - >例如“SuperTextBox”,其依赖属性为“SuperValue”。

控制XAML代码:

<UserControl x:Class="WpfApplication2.SuperTextBox"
             ...
             Name="Root">
    <TextBox Text="{Binding SuperValue, ElementName=Root, UpdateSourceTrigger=PropertyChanged}" />
</UserControl>

代码背后:

public partial class SuperTextBox : UserControl
{
    public SuperTextBox()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty SuperValueProperty = DependencyProperty.Register(
        "SuperValue",
        typeof(string),
        typeof(SuperTextBox),
        new FrameworkPropertyMetadata(string.Empty)
    );

    public string SuperValue
    {
        get { return (string)GetValue(SuperValueProperty); }
        set { SetValue(SuperValueProperty, value); }
    }
}

好的,现在测试!

从TextBox.Text绑定到SuperTextBox.SuperValue

    <TextBox x:Name="Test1" Text="{Binding ElementName=Test2, Path=SuperValue, UpdateSourceTrigger=PropertyChanged}" />
    <local:SuperTextBox x:Name="Test2" Grid.Row="2"/>

测试也是正确的! 当我在TextBox中写东西时,SuperTextBox正在更新。 当我在SuperTextBox中编写时,TextBox正在更新。 一切都好!

现在出了问题:
从SuperTextBox.SuperValue绑定到TextBox.Text

    <TextBox x:Name="Test1"/>
    <local:SuperTextBox x:Name="Test2" SuperValue="{Binding ElementName=Test1, Path=Text, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2"/>

在这种情况下,当我在SuperTextBox中写东西时,TextBox没有更新! 在此输入图像描述

我怎样才能解决这个问题?

PS:问题很长,我很抱歉,但我试着准确描述我的问题。

将绑定模式更改为TwoWay。

因为在前两种情况下, Test1知道何时需要更新自己而不是第三种情况。 只有Test2知道它应该在第三种情况下更新。 这就是为什么在第三种情况下需要TwoWay模式的原因。

编辑

  • 第一种情况是在幕后工作,xaml挂钩到PropertyDescriptor公开的AddValueChanged事件。 对于它的工作的原因参考此链接这里

一个工作而另一个不工作的原因是因为TextBoxText依赖属性被定义为默认绑定TwoWay ,而您的依赖属性SuperValue不是。 如果希望目标更新源以及更新目标的源,则需要使用TwoWay绑定。

要解决此问题,您可以将FrameworkPropertyMetadataOptions.BindsTwoWayByDefault添加到SuperValue's元数据中,如下所示:

public static readonly DependencyProperty SuperValueProperty = DependencyProperty.Register(
    "SuperValue",
    typeof(string),
    typeof(SuperTextBox),
    new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM