我有一个数据网格
<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;
}
}
问题是当我设置文件名时,observable集合还没有更新。 我将用图片解释:
所以我添加了aaaa和bbb现在我想用上面的代码强制使用文件名,但是当我这样做时,绑定动作还没有在可观察集合上完成,因此aaaa和bbbb不存在。
简而言之,如何告诉绑定的datagrid更新绑定??
提前致谢 帕特里克
答案 0 :(得分:1)
您的CfgPartPrograms类应实现INotifyPropertyChanged接口,并在数据绑定属性设置为新值时引发PropertyChanged事件:https://msdn.microsoft.com/en-us/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));
}
}
答案 1 :(得分:0)