【问题标题】:Change wpf data grid row background color when checkbox is checked选中复选框时更改 wpf 数据网格行背景颜色
【发布时间】:2015-10-11 00:05:47
【问题描述】:

当给定行的复选框被选中时,我试图更改我的数据网格行的颜色,当未选中时,它应该将值重置为前一个。

我正在使用 MVVM 来实现上述功能。

我的 XAML 代码:-

 <Window.Resources>
        <Style x:Key="RowStyle"  TargetType="{x:Type DataGridRow}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding DataContext.IsChecked, UpdateSourceTrigger=PropertyChanged}" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>

 </Window.Resources>

<Grid>
      <DataGrid Name="lbUsers" ItemsSource="{Binding  Data}" CanUserAddRows="False" Grid.Column="1" Grid.Row="1"  SelectedIndex="{Binding SelectionIndexChange, Mode=TwoWay}" AutoGenerateColumns="False">

            <DataGrid.Columns>

                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox Width="45" Height="20" Command="{Binding ElementName=lbUsers,Path=DataContext.IsChecked}" ></CheckBox>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>

        </DataGrid>
</Grid>

下面是视图模型代码:

        public ViewModel ()
        {
            Data = new ObservableCollection<CommonData>
            {

            };

        }



    private ObservableCollection<CommonData> _data;
        public ObservableCollection<CommonData> Data
        {
            get
            {
                if (_data == null)
                {
                    _data = new ObservableCollection<CommonData>()
                    {

                    };

                }

                return _data;
            }
            set
            {
                if (value != this._data)
                {
                    this._data = value;

                    NotifyPropertyChanged("Data");
                }
            }
        }



        private bool _isChecked;
        public bool IsChecked
        {
            get { return _isChecked; }
            set { this._isChecked = value; NotifyPropertyChanged("IsChecked"); }
        } 

请让我知道我做错了什么才能让给定的功能正常工作。

提前致谢,如有遗漏请告知。

【问题讨论】:

  • 您是否尝试过删除 DataContext.来自绑定表达式?
  • 或者,您是否分配了数据上下文?
  • 我试过它不工作..
  • 你在哪里分配数据上下文?
  • 检查输出窗口是否有任何绑定错误。如果有任何错误,请修复它们。

标签: c# wpf xaml mvvm wpfdatagrid


【解决方案1】:

几件事:

您已为样式分配了x:Key,但没有在DataGrid 上使用它。删除键使其成为所有DataGridRow 的默认样式,或将其添加到网格中:

RowStyle="{StaticResource RowStyle}"

DataTrigger 绑定中,您还需要添加

ElementName=lbUsers

此外,您的Checkbox 绑定不正确——这不是通过Command 完成的。你需要改变

Command={Binding...

IsChecked={Binding...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 2021-01-12
    • 2022-12-18
    • 2014-09-24
    • 1970-01-01
    相关资源
    最近更新 更多