繁体   English   中英

如何通过手动更新来处理可观察的集合绑定的数据网格

[英]How to cope with a observable collection binded datagrid with manual update

我有一个数据网格

<DataGrid Name="dtgFeatures" Height="100" Margin="10" ColumnWidth="*" CanUserAddRows="True" MouseLeftButtonUp="DtgFeatures_MouseLeftButtonUp"/>

绑定到可观察的集合

ObservableCollection<CfgPartPrograms> obcCfgPartPrograms = new ObservableCollection<CfgPartPrograms>();

[Serializable]
public class CfgPartPrograms
{
    public CfgPartPrograms() { }
    public string Group{ get; set;}
    public string Description{ get; set;}
    public string Filename{ get; set;}<------set with openfiledialog
    public string Notes{ get; set;}
}

现在,由于我希望能够使用openfileDialog插入文件名,因此添加了以下代码:

private void DtgFeatures_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    int column = (sender as DataGrid).CurrentCell.Column.DisplayIndex;
    if ( column == 2)
    {
        OpenFileDialog ofdPP = new OpenFileDialog();
        if (ofdPP.ShowDialog() == true)
        {
            if (obcCfgPartPrograms.Count == 0)
                obcCfgPartPrograms.Add(new CfgPartPrograms() { Filename = ofdPP.FileName });
            else
                obcCfgPartPrograms[selectedIndex].Filename = ofdPP.FileName;
            dtgFeatures.ItemsSource = null;
            dtgFeatures.ItemsSource = obcCfgPartPrograms;
        }
    }

问题是,当我设置文件名时,可观察的集合尚未更新。 我将用图片进行说明:

在此处输入图片说明

因此,我现在添加了aaa和bbb,我想使用上面的代码强制使用文件名,但是当我这样做时,可观察的集合还没有执行bind操作,因此aaa和bbbb不存在。

在此处输入图片说明

简而言之,如何告诉绑定的数据网格更新绑定?

在此先感谢Patrick

每当数据绑定属性设置为新值时,您的CfgPartPrograms类都应实现INotifyPropertyChanged接口并引发PropertyChanged事件: https ://msdn.microsoft.com/zh-cn/library/system.componentmodel.inotifypropertychanged(v=vs .110).aspx

[Serializable]
public class CfgPartPrograms : System.ComponentModel.INotifyPropertyChanged
{
    public CfgPartPrograms() { }

    public string Group { get; set; }
    public string Description { get; set; }
    private string _fileName;

    public string Filename
    {
        get { return _fileName; }
        set { _fileName = value; NotifyPropertyChanged(); }
    }

    public string Notes { get; set; }

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
    }
}

我在这里找到它:我错过了

dtgFeatures.CommitEdit(DataGridEditingUnit.Row, true);

命令

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM