Okay, I am brand new to WPF. I am trying to bind a collection to a DataGrid
control. When I run the program, the cells in the DataGrid
are blank, even though there is data in the collection.
I have read all of the relevant articles on MSDN -- multiple times. I've searched Stack Overflow with no luck. 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 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. If I edit a cell in the DataGrid, the FileName
property for the relevant object will be updated in the collection. 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 string FileName {
get { return fileName; }
set
{
fileName = value;
OnPropertyChanged("FileName");
}
}
public string Path { get; set; }
public string Extension { get; set; }