"UpdateSourceTrigger"属性的概念,如何在WPF中使用它?

Jee*_*att 7 wpf binding

我有一个TextBlock,绑定了一个Object,当我更新对象的属性时,它没有在UI上重新发布,为什么?

码:

在Windows1.xaml中

<TextBlock Name="txtName" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" Width="100" Height="20" Margin="12,23,166,218" />
Run Code Online (Sandbox Code Playgroud)

在Windows.xaml.cs中

public partial class Window1 : Window
{
    Employee obj ;
    public Window1()
    {            
        InitializeComponent();
        obj = new Employee();
        obj.Name = "First";
        txtName.DataContext = obj;
    }

    private void btnUpdate_Click(object sender, RoutedEventArgs e)
    {
        obj.Name = "changed";            
    }
}
public class Employee : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private string _name;
    public string Name
    {
        set 
        {
            this._name = value;
            OnPropertyChanged(Name);
        }
        get { return this._name; }
    }

    protected void OnPropertyChanged(string name)
    {

        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {

            handler(this, new PropertyChangedEventArgs(name));

        }

    }        
}
Run Code Online (Sandbox Code Playgroud)

Ken*_*art 8

OnPropertyChanged(Name);
Run Code Online (Sandbox Code Playgroud)

应该:

OnPropertyChanged("Name");
Run Code Online (Sandbox Code Playgroud)

否则,如果名称设置为"Kent",则表示"肯特"属性已更改,这显然不存在属性更改事件.

至于UpdateSourceTrigger,那只适用于来源.您绑定的属性是目标,而不是源.并且TextBlock更新其源代码没有意义,因为用户无法修改TextBlock文本.TextBox另一方面,A 是有道理的.在这种情况下,UpdateSourceTrigger确定将文本TextBox推回到源属性的点(例如,当用户键入每个字符时,或者当它们离开时TextBox).