这是一种做法。 IDK,如果它是最好的方式,但它的工作原理,它已经过了几个小时,因为你问这么... ...
你的DataGridCell充满了边框/文本框,所以我假设你想改变文本框的背景颜色因为你不会看到DataGridCell的背景。
既然你提到可能有更复杂的场景在未来,我用了一个multibinding与转换器和(通过使用绑定</>)和它的文本值在文本框的datacontext传递。
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text}">
<TextBox.Resources>
<local:ValidationBGConverter x:Key="ValidationBGConverter" />
</TextBox.Resources>
<TextBox.Style>
<Style TargetType="TextBox">
<Setter Property="Background">
<Setter.Value>
<MultiBinding Converter="{StaticResource ValidationBGConverter}">
<Binding />
<Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Content.Text" />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</TextBox.Style>
</TextBox>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
这里是转换器:
public class ValidationBGConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.Length != 2)
return Brushes.Black;
var datacontext = values[0] as ViewData; // Or whatever the textbox's datacontext object is
if (datacontext != null) // If null, probably the new item row
{
var txt = values[1] as string; // Textbox text
if (string.IsNullOrWhiteSpace(txt))
return Brushes.Red;
if (txt.Length < 3)
return Brushes.Pink;
if (txt.Length > 5)
return new LinearGradientBrush(Colors.White, Colors.Blue, 90.0);
}
return Brushes.White;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
而且,截图:
![enter image description here](https://i.stack.imgur.com/phR8a.png)
非常有帮助,谢谢。特别是关于传递DataContext作为参数的部分: 。 –
Number8
不客气。你能接受答案吗?谢谢。 –