从属性到UI的WPF复选框twoway绑定不适用于propertychanged事件

时间:2015-03-16 21:53:51

标签: c# wpf telerik-grid

我在Telerik Grid视图控件的复选框数据列中使用twoway绑定。当我在UI上更改复选框的状态时,它正常工作,触发属性更改事件。但我也反过来说,在更改后面代码的属性值时,复选框状态也应该在UI上更新。

<Button x:Name="btn1" Grid.Row="0" Content="Refresh" Click="btn1_Click" Width="100" Margin="0,5"/>
    <telerik:RadGridView Grid.Row="1"  x:Name="gridView" ShowGroupPanel="False" IsFilteringAllowed="False" SelectionMode="Multiple">
        <telerik:RadGridView.Columns>
            <telerik:GridViewDataColumn Width="70" Header="Color">
                <telerik:GridViewDataColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <CheckBox  IsChecked="{Binding ChangeValue, Mode=TwoWay}" Margin="3"/>
                        </StackPanel>
                    </DataTemplate>
                </telerik:GridViewDataColumn.CellTemplate>
            </telerik:GridViewDataColumn>
            <telerik:GridViewDataColumn Header="Data" DataMemberBinding="{Binding dataVal}" IsReadOnly="True"/>
        </telerik:RadGridView.Columns>
    </telerik:RadGridView>
</Grid>

背后的代码在

之下
public partial class MainWindow : Window
{
    List<Data> dataSource = new List<Data>();
    public MainWindow()
    {
        InitializeComponent();            
        for (int i = 0; i < 10; i++)
        {
            data d = new Data();
            d.DataVal= "Data " + (i + 1);
            dataSource.Add(d);
        }
        this.gridView.SelectedItems.Clear();
        PopulateGridView();
    }
    private void PopulateGridView()
    {
        foreach (Data d in dataSource)
        {
            d.DataVal= false;
        }

        this.gridView.ItemsSource = dataSource;
        List<Data> selectedItems = new List<Data>();
        selectedItems.Add(dataSource[0]);
        this.gridView.Select(selectedItems);
    }

    private void btn1_Click(object sender, RoutedEventArgs e)
    {
        PopulateGridView();
    }

}

public class Data: INotifyPropertyChanged
{
    public Data()
    {
        DataVal = string.Empty;
    }
    public string DataVal { get; set; }

    public bool ChangeValue
    {
        get { return changevalue; }
        set
        {
            if (value != changevalue)
            {
                changevalue= value;
                if (ApplyPropertyChanged!= null)
                {
                    ApplyPropertyChanged(this, new PropertyChangedEventArgs("ChangeValue"));
                }
            }
        }
    }

    private bool changevalue;
    public event PropertyChangedEventHandler ApplyPropertyChanged;

}

单击“刷新”按钮时,我希望所有复选框都未选中,但是当我在PopulateGridView中将ChangeValue设置为false时,它们不会更新。请建议我如何实现这一目标。

1 个答案:

答案 0 :(得分:3)

您需要指定何时更新UI,在本例中为onpropertychanged

       <CheckBox  IsChecked="{Binding ChangeValue, Mode=TwoWay, UpdateSourceTrigger="PropertyChanged"}" Margin="3"/>