我有两种WPF单元格样式,并且想要通过一个转换器来应用它们。在下面的示例中,我试图更改背景颜色(在实际应用程序中,我将更改更多内容,但这不是问题的重点,因此我只是简化了一下)。
<Style TargetType="{x:Type DataGridCell}" x:Key="WinCellStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border x:Name="border"
Background="LightGreen"
BorderBrush="Transparent"
BorderThickness="1"
SnapsToDevicePixels="True">
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type DataGridCell}" x:Key="LossCellStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border x:Name="border"
Background="LightSalmon"
BorderBrush="Transparent"
BorderThickness="1"
SnapsToDevicePixels="True">
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我现在有一个转换器:
public class AmountToCellStyleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var valueAsDecimal = (decimal?) value;
if (valueAsDecimal > 0)
{
return Application.Current.FindResource("WinCellStyle") as Style;
}
return Application.Current.FindResource("LossCellStyle") as Style;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
那么我如何在单元格样式中调用它呢?
XAML:
<Window.Resources>
<converter:AmountToCellStyleConverter x:Key="AmountToCellStyleConverter"/>
</Window.Resources>
...
<DataGridTextColumn CellStyle="{Binding ??? What goes here}" Binding="{Binding Path=MarketBookSelection.TotalWagerStakeWin, StringFormat=N2}" Header="Stake Win" Width="Auto" />
也许答案是这不可能实现,我需要走其他路线吗?
DataGridColumns
不在与DataGrid相同的VisualTree
中。因此,默认情况下,它不会继承DataGrid的DataContext
,*Binding
*也无法工作。除了我的答案之外,你还可以使用一个代理来继承DataContext,具体讨论请参见这里
。 - Anatoliy Nikolaev