绑定到DependencyProperty没有结果

时间:2012-10-20 16:30:56

标签: c# wpf binding user-controls dependency-properties

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

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

XAML代码:

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

结果很好 - 当我在第一个TextBox中写一些东西时 - &gt;第二个TextBox正在更新(反过来)。

enter image description here

我创建了新控件 - &gt;例如“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没有更新! enter image description here

我该如何解决这个问题?

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

3 个答案:

答案 0 :(得分:1)

将绑定模式更改为TwoWay。

答案 1 :(得分:1)

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

修改

  • 第一种情况是在幕后工作,xaml挂钩 AddValueChanged公开的PropertyDescriptor事件。为了 其工作原因请参考此链接here

答案 2 :(得分:1)

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

要解决此问题,您可以将TwoWay添加到SuperValue元数据,如下所示:

FrameworkPropertyMetadataOptions.BindsTwoWayByDefault