如何在WPF中的数据网格中选择单元格时更改文本的背景颜色
答案 0 :(得分:0)
你可以使用触发器来实现这一目标。
<DataGrid.CellStyle>
<Style TargetType="DataGridCell" >
<Style.Triggers>
<Trigger Property="IsEditing" Value="True">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridCell">
<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text, Mode=TwoWay, UpdateSourceTrigger=Default}"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Padding="0" BorderThickness="0" Background="SeaGreen"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
<Style.Triggers>
</Style>
</DataGrid.CellStyle>
答案 1 :(得分:0)
如果你在这些DataGridRows上有一个TextBox,这是一个完整的例子:
<Window x:Class="DataGridCellsBackground.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid SelectionUnit="Cell"
ItemsSource="{Binding items}"
AutoGenerateColumns="False">
<DataGrid.Resources>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Name}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
所有的魔力都发生在这里:
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
一个简单的Person类:
public class Person : INotifyPropertyChanged
{
private string _Name;
public string Name
{
get { return _Name; }
set
{
_Name = value;
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
用于测试目的的代码:
public partial class MainWindow : Window
{
public ObservableCollection<Person> items { get; set; }
public MainWindow()
{
InitializeComponent();
items = new ObservableCollection<Person>();
items.Add(new Person() { Name = "FirstName" });
items.Add(new Person() { Name = "SecondName" });
this.DataContext = this;
}
}
案例2
您将DataTemplate定义为不可编辑,但仍想选择单元格:
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
您将风格改为:
<Style TargetType="DataGridCell">
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
为什么这样工作?
由于DataGrid的SelectionUnit属性设置为Cell,因此只会影响单个单元格。如果SelectionUnit设置为FullRow,则背景颜色将应用于所选行中的所有单元格。