[英]Binding an ObservableCollection to a DataGrid
Okay, I am brand new to WPF. 好的,我是WPF的新手。 I am trying to bind a collection to a
DataGrid
control. 我试图将集合绑定到
DataGrid
控件。 When I run the program, the cells in the DataGrid
are blank, even though there is data in the collection. 当我运行程序时,
DataGrid
中的单元格是空白的,即使集合中有数据。
I have read all of the relevant articles on MSDN -- multiple times. 我已多次阅读MSDN上的所有相关文章。 I've searched Stack Overflow with no luck.
我搜索Stack Overflow没有运气。 I've spent a day and a half on this, and am just as confused as I was when I first started.
我花了一天半的时间,就像我刚开始时一样困惑。 Here is what I have so far.
这是我到目前为止所拥有的。
The XAML for the DataGrid
control: DataGrid
控件的XAML:
<DataGrid AutoGenerateColumns="False" Margin="0,85,0,0" Name="dtaCompilation" ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding FileName}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
And here is the class containing my collection: 这是包含我的集合的类:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
dtaCompilation.DataContext = Compilation;
}
ObservableCollection<CompilationFile> Compilation = new ObservableCollection<CompilationFile>();
public class CompilationFile : INotifyPropertyChanged
{
public CompilationFile(string setPath, string setFile, string setExt)
{
this.Path = setPath;
this.FileName = setFile;
this.Extension = setExt;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private string fileName;
string FileName {
get { return fileName; }
set
{
fileName = value;
OnPropertyChanged("FileName");
}
}
string Path { get; set; }
string Extension { get; set; }
}
}
The end result is to have a DataGrid
that shows only the FileName
property for each CompilationFile
object in the Compilation
collection. 最终结果是有一个
DataGrid
,它只显示Compilation
集合中每个CompilationFile
对象的FileName
属性。 If I edit a cell in the DataGrid, the FileName
property for the relevant object will be updated in the collection. 如果我在DataGrid中编辑单元格,则相关对象的
FileName
属性将在集合中更新。 What exactly do I need to do to get this to work with the code above? 我需要做什么才能使其与上面的代码一起使用?
Set the properties you want databound to public 将您想要数据绑定的属性设置为public
public string FileName {
get { return fileName; }
set
{
fileName = value;
OnPropertyChanged("FileName");
}
}
public string Path { get; set; }
public string Extension { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.