簡體   English   中英

選中 WPF Datagrid 復選框列

[英]WPF Datagrid checkbox column checked

我的數據網格復選框列:

                    <DataGridTemplateColumn MaxWidth="45">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox x:Name="check_tutar"  VerticalAlignment="Center" HorizontalAlignment="Center" HorizontalContentAlignment="Center" Checked="check_tutar_Checked"></CheckBox>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

我想訪問此復選框並更改選中的屬性。 我嘗試使用默認方法: check_tutar.IsChecked = false;

但是沒有用,因為我無法使用名稱訪問復選框。 如何更改數據網格列復選框選中的屬性?

您應該將CheckBoxIsChecked屬性綁定到數據對象的bool屬性,並設置此屬性,而不是嘗試訪問CheckBox控件本身:

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <CheckBox x:Name="check_tutar" IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}" />
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

數據類應實現INotifyPropertyChanged接口,並在設置IsChecked屬性以使其正常工作時發出更改通知:

public class YourClass : INotifyPropertyChanged
{
    private bool _isChecked;
    public bool IsChecked
    {
        get { return _isChecked; }
        set { _isChecked = value; NotifyPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

然后,您可以通過設置相應對象的IsChecked屬性來簡單地選中/取消選中DataGrid一行的CheckBox ,例如:

List<YourClass> theItems = new List<YourClass>(0) { ... };
dataGrid1.ItemsSource = theItems;

//check the first row:
theItems[0].IsChecked = true;

基本上,這就是WPF和DataGrid的工作方式。

private void ChkSelect_Checked(object sender, RoutedEventArgs e)
    {
        DataRowView row;
        row = (DataRowView)((CheckBox)e.OriginalSource).DataContext;
        row["DeleteRule"] = "True";
    }

    private void ChkSelect_Unchecked(object sender, RoutedEventArgs e)
    {
        DataRowView row;
        row = (DataRowView)((CheckBox)e.OriginalSource).DataContext;
        row["DeleteRule"] = "False";
    }

此解決方案沒有綁定,您可以使用上面的代碼獲取選中的行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM