数据网格单元格值的Wpf datagrid update datacontext已更改

时间:2011-06-12 13:06:50

标签: .net wpf

我有DataGrid,用户可编辑,当用户编辑单元格时,我想要更改datacontext。我该怎么办?

<my:DataGrid Height="279" Name="dataGrid1" Width="210" AutoGenerateColumns="False" ItemsSource="{Binding Path=Props}" CellEditEnding="dataGrid1_CellEditEnding">
    <my:DataGrid.Columns>
                    <my:DataGridTextColumn Header="Property" Width="1*" IsReadOnly="True" Binding="{Binding Path=Name}"></my:DataGridTextColumn>
                    <my:DataGridTextColumn Header="Value" Width="1*" Binding="{Binding Path=Value}" ></my:DataGridTextColumn>
    </my:DataGrid.Columns>
</my:DataGrid>
class ConfigModel : INotifyPropertyChanged
{
    private ObservableCollection<Prop> props;

    public ObservableCollection<Prop> Props
    {
        get { return props; }
        set { props = value; OnPropertyChanged("Props"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string Props)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(Props));
    }
}


public class Prop {
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    private string value;

    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

}

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        InitializeConfiguration();            
    }

    private void InitializeConfiguration(){
        var conf = new ObservableCollection<Prop>();
        conf.Add(new Prop() { Name = "path", Value = Properties.Settings.Default.Properties["path"].DefaultValue.ToString() });
        conf.Add(new Prop(){ Name = "host", Value = Properties.Settings.Default.Properties["host"].DefaultValue.ToString()});
        DataContext = new ConfigModel() { Props = conf };
    }

1 个答案:

答案 0 :(得分:1)

当集合发生变化时, PropertyChanged 事件会被提升(例如,添加或删除项目),但是当属性之一时项目(在您的示例中为Prop类型)更改。为此,您需要在支持类上实施INotifyPropertyChanged