4
我有兩個WPF單元格樣式,我想基於轉換器應用它們。 我是我的示例下面我試圖改變背景顏色(在實際應用程序中,我會改變比這更多,但這不是問題的關鍵,所以我只是簡化)。使用轉換器設置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" />
也許答案是,這是不可能的,我需要去了一些其他的途徑?
這是一種享受,只是想知道是否有任何理由的細胞風格不能採取更便宜的綁定? – DermFrench
@DermFrench:這是因爲DataGridColumns與DataGrid不在同一個VisualTree中。因此,默認情況下,它不會繼承DataGrid的'DataContext'和*'Binding' *不起作用。除了我的回答之外,還可以使用代理來討論DataContext的繼承[[here']](http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to -data-當最的datacontext-IS-未繼承/)。 –