3

我偶尔会遇到一个问题。这是一个简单的例子:

Xaml 代码:

<Window x:Class="WPFProperties.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"
        x:Name="root">
    <Grid>
        <TextBox Text="{Binding Text,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,ElementName=root}"/>
    </Grid>
</Window>

后面的代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    //// Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
    //public static readonly DependencyProperty TextProperty =
    //    DependencyProperty.Register("Text", typeof(string), typeof(MainWindow), new UIPropertyMetadata(null));

    private string _text;

    public string Text
    {
        get { return _text; }
        set 
        {
            if (this._text == value) return;
            _text = value;

            this.DoSomething();
        }
    }

    private void DoSomething()
    {
        // Do Someting
    }
}

在文本框上键入时,可以调用方法 DoSomething()。但是,一旦我取消注释依赖属性“Text”,它就永远不会被调用。

注意:我知道依赖属性的基本用法。

4

2 回答 2

2

好吧,AFAIK 这里没有发生正常的属性声明,因为当声明 DP 时,static它会在一开始就被初始化,甚至在创建普通对象之前就已经被初始化并且它具有优先权。

因此,类中的属性仅被视为普通的 DP 辅助属性,而不是看起来像新的类成员属性。因此,绑定内部只是使用内部SetValue(...)GetValue(...)直接绕过您的覆盖,这是 DP 的正常行为。

当没有声明 DP 时,这将成为该类的正常属性,反过来我们会看到您的 DoSomething()调用。

同样,如果我们调用 MainWindow 的构造函数,即使没有注释 DP 定义Text = "Anything",我们也可以看到DoDomething()被调用,因为这是 DP 在调用本地助手时的工作方式。只是绑定使用基本定义的

于 2013-05-17T12:46:42.167 回答
2

您需要使用回调创建 UIPropertyMetaData (PropertyChangedCallback propertyChangedCallback),它应该是静态方法,您应该在其中调用传递的 DependancyObject 的更新属性

示例在这里解释:MSDN

于 2013-05-17T12:12:44.017 回答