【问题标题】:Multiple Row Selection In WPF DataGrid Programmatically以编程方式在 WPF DataGrid 中选择多行
【发布时间】:2012-10-23 00:47:27
【问题描述】:

嗨,我有一个 wpf 数据网格,它有两列说

key    Value
1       abc
2       xyz
3       pqr

我有一个复选框,其值相当于列中的键。如果选中相关键,则必须选择对应的行。选中多个复选框,选择数据网格中的多行。

【问题讨论】:

    标签: wpf wpfdatagrid


    【解决方案1】:

    Xaml:

    <StackPanel>
        <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding List}">
            <DataGrid.Columns>
                <DataGridCheckBoxColumn Header="Check" 
                    Binding="{Binding IsCheck, UpdateSourceTrigger=PropertyChanged}"/>
                <DataGridTextColumn Header="Key" Binding="{Binding Key}"/>
                <DataGridTextColumn Header="Value" Binding="{Binding Value}"/>
            </DataGrid.Columns>
        </DataGrid>
        <CheckBox Content="1" DataContext="{Binding List[0]}" IsChecked="{Binding IsCheck}"/>
        <CheckBox Content="2" DataContext="{Binding List[1]}" IsChecked="{Binding IsCheck}"/>
        <CheckBox Content="3" DataContext="{Binding List[2]}" IsChecked="{Binding IsCheck}"/>
    </StackPanel>
    

    后面的代码:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            //fill 'List' here...
            DataContext = this;
            InitializeComponent();
        }
        //List Observable Collection
        private ObservableCollection<Row> _list = new ObservableCollection<Row>();
        public ObservableCollection<Row> List { get { return _list; } }
    }
    

    行类:

    public class Row: DependencyObject
    {
        //Key Dependency Property
        public int Key
        {
            get { return (int)GetValue(KeyProperty); }
            set { SetValue(KeyProperty, value); }
        }
        public static readonly DependencyProperty KeyProperty =
            DependencyProperty.Register("Key", typeof(int), typeof(Row), new UIPropertyMetadata(0));
        //Value Dependency Property
        public string Value
        {
            get { return (string)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(string), typeof(Row), new UIPropertyMetadata(""));
        //IsCheck Dependency Property
        public bool IsCheck
        {
            get { return (bool)GetValue(IsCheckProperty); }
            set { SetValue(IsCheckProperty, value); }
        }
        public static readonly DependencyProperty IsCheckProperty =
            DependencyProperty.Register("IsCheck", typeof(bool), typeof(Row), new UIPropertyMetadata(false));
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-30
      • 2011-04-22
      • 2021-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多