当前位置: 首页> 文旅> 美景 > 上海网站关键排名_dreamweaver序列号免费_最佳磁力搜索引擎_百度指数资讯指数是指什么

上海网站关键排名_dreamweaver序列号免费_最佳磁力搜索引擎_百度指数资讯指数是指什么

时间:2025/8/23 13:00:55来源:https://blog.csdn.net/m0_51005282/article/details/142384647 浏览次数:0次
上海网站关键排名_dreamweaver序列号免费_最佳磁力搜索引擎_百度指数资讯指数是指什么

WPF DataGrid 动态修改某一个单元格的样式

 <DataGrid Name="main_datagrid_display" Width="1267" Height="193" Grid.Column="1"ItemsSource="{Binding DataGridModels}"><DataGrid.Columns><!--ElementStyle 设置元素样式--><DataGridTextColumn Header="状态" Width="*" IsReadOnly="True" Binding="{Binding ZhuangTai}" ElementStyle="{StaticResource textblock_textalignment_center}"></DataGridTextColumn></DataGrid.Columns>
</DataGrid>

  对于 DataGrid 某一行,如果我们想要动态的对指定单元格的样式进行修改,按照上述代码,是很难去实现的,但是有时候需求就需要我们动态的修改指定的单元格,例如我这里动态对指定单元格修改前景色,所对应的绑定数据定义如下:

public class DataGridModel : INotifyPropertyChanged
{private System.Windows.Media.Brush _foreColor;public System.Windows.Media.Brush ForeColor{get { return _foreColor; }set{if (_foreColor != value){_foreColor = value;if (null != PropertyChanged){PropertyChanged(this, new PropertyChangedEventArgs("ForeColor"));}}}}public event PropertyChangedEventHandler? PropertyChanged;public DataGridModel(System.Windows.Media.Brush color){ForeColor = color;}
}

方法一:使用 DataGridTemplateColumn

<DataGrid Name="main_datagrid_display" Width="1267" Height="193" Grid.Column="1"ItemsSource="{Binding DataGridModels}"><DataGrid.Columns><!--DataGridTemplateColumn 实现--><DataGridTemplateColumn Header="状态" Width="*" IsReadOnly="True"><DataGridTemplateColumn.CellTemplate><DataTemplate><Border><TextBox Text="{Binding ZhuangTai}" Foreground="{Binding ForeColor}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></TextBox></Border></DataTemplate></DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn><!--DataGridTemplateColumn 实现--></DataGrid.Columns>
</DataGrid>

  这里我在 xaml 中为 Foreground 绑定 ForeColor 属性,在后台就可以动态修改其前景色,下同。

方法二:修改 DataGridTextColumn .ElementStyle

<DataGrid Name="main_datagrid_display" Width="1267" Height="193" Grid.Column="1"ItemsSource="{Binding DataGridModels}"><DataGrid.Columns><!--DataGridTextColumn .ElementStyle 实现--><DataGridTextColumn Header="状态" Width="*" IsReadOnly="True" Binding="{Binding ZhuangTai}"><DataGridTextColumn.ElementStyle><Style TargetType="TextBlock"><Setter Property="Foreground" Value="{Binding ForeColor}"></Setter></Style></DataGridTextColumn.ElementStyle></DataGridTextColumn><!--DataGridTextColumn .ElementStyle 实现--></DataGrid.Columns>
</DataGrid>

  以上两种方式得到的结果一样,可以根据实际情况再稍微调整下格式:
在这里插入图片描述
结语:如果修改变动不至于修改一整个单元格的话,推荐使用方法二。

关键字:上海网站关键排名_dreamweaver序列号免费_最佳磁力搜索引擎_百度指数资讯指数是指什么

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: