WPF数据绑定在Datagrid中的Checkbox上失败

时间:2014-01-13 22:43:42

标签: c# wpf data-binding properties datagrid

我使用带有Checkbox的Datagrid,我想将它绑定到名为Part的类:

public class Part 
{
    public bool DoImport { get; set; }
}

我的窗口WPF是:

<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>

在那里,我使用一个名为Select All的按钮,如果单击该按钮,应立即检查所有复选框:

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");
        }
    }
}

但是当我点击按钮时没有任何反应。为什么呢?

1 个答案:

答案 0 :(得分:2)

您需要在包含INotifyPropertyChanged属性的类中实现DoImport

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));
}