我偶尔会遇到一个问题。这是一个简单的例子:
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”,它就永远不会被调用。
注意:我知道依赖属性的基本用法。