绑定对象更改时刷新视图

时间:2016-05-12 12:40:59

标签: c# wpf

我在WPF中有一个文本框,它有" Text"绑定到字符串的属性" EmployeeSource.ID"使用Mode = TwoWay。我的问题是,当我更改EmployeeSource对象时,绑定不起作用。我的做法有什么问题?

XAML

<TextBox x:Name="NameTextBox" Margin="5,5,10,5" TextWrapping="Wrap"
Text="{Binding SelectedEmployee.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Grid.Row="1" Grid.Column="1" />

代码背后

private Employee _selectedEmployee;

public Employee SelectedEmployee
{
    get { return _selectedEmployee; }
    set
    {
        _selectedEmployee = value;
        UpdateTextBoxes();
    }
}

private void UpdateTextBoxes()
{
    NameTextBox.Text = SelectedEmployee?.Name;
}

1 个答案:

答案 0 :(得分:0)

请尝试以下代码。您需要实现INotifyPropertyChanged接口以便在WPF中实现数据绑定。这是WPF数据绑定和MVVM模式的基本概念。这应该适合你。

代码背后:

public class YourClassName : INotifyPropertyChanged
{
    // These fields hold the values for the public properties.
    private Employee _selectedEmployee;

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

    // The constructor is private to enforce the factory pattern.
    private YourClassName()
    {
        _selectedEmployee = new Employee();
    }

    public Employee selectedEmployee
    {
        get
        {
            return this._selectedEmployee;
        }
        set
        {
            if (value != this._selectedEmployee)
            {
                this._selectedEmployee = value;
                NotifyPropertyChanged("selectedEmployee");
            }
        }
    }
}

XAML:

<TextBox x:Name="NameTextBox" Margin="5,5,10,5" TextWrapping="Wrap"
Text="{Binding selectedEmployee.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Grid.Row="1" Grid.Column="1" />