Reputation: 204756
I use a Datagrid with a Checkbox and I want to bind it to a class named Part
:
public class Part
{
public bool DoImport { get; set; }
}
My Window WPF is:
<Window x:Class="CompareWindow">
<Grid>
<DataGrid x:Name="CompareGrid" ItemsSource="{Binding}" >
<DataGrid.Columns>
<DataGridCheckBoxColumn Header="Import" Width="100" IsReadOnly="False" Binding="{Binding Path=DoImport, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</DataGrid.Columns>
</DataGrid>
<Button x:Name="SelectAllBtn" Content="Select All" Click="SelectAllButton_Click"/>
</Grid>
</Window>
In there I use a Button named Select All
that should check all Checkboxes at once if clicked:
public partial class CompareWindow : Window, INotifyPropertyChanged {
public CompareWindow(Part somePart) {
_changedParts = new ObservableCollection<Part>();
_changedParts.Add(somePart);
CompareGrid.DataContext = _changedParts;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name) {
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
private void SelectAllButton_Click(object sender, RoutedEventArgs e) {
ChangedParts.ToList().ForEach(x => x.DoImport = true);
}
private ObservableCollection<Part> _changedParts;
public ObservableCollection<Part> ChangedParts {
get { return _changedParts; }
set {
_changedParts = new ObservableCollection<Part>();
foreach (var part in value) {
_changedParts.Add(part);
}
OnPropertyChanged("ChangedParts");
}
}
}
But nothing happens when I click the button. Why?
Upvotes: 0
Views: 186
Reputation: 2682
You need to implement INotifyPropertyChanged
in the class that contains the DoImport
property.
private bool doImport;
public bool DoImport
{
get { return doImport; }
set
{
doImport = value;
this.OnPropertyChanged("DoImport");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
Upvotes: 2