【发布时间】:2011-12-07 22:51:38
【问题描述】:
我有一个转换器,它接受一个十进制值并将其转换为画笔(红色表示负输入,黑色表示正输入)。我还创建了一种样式,我想将其应用于所有采用十进制值的DataGridTextColumn。如果我为每个 DataGridTextColumn 内联样式,我可以简单地在绑定表达式中的 Datacontext 上指定相关属性。但是我不想内联样式并将其简单地作为资源,这样我就可以将 CellStyle 设置为资源。问题是我不知道在 Foreground 属性的值的绑定中放入什么。我希望能够将它绑定到应用它的单元格所绑定的值。
这是我所拥有的:
<Window.Resources>
<!-- This converter takes a decimal value and returns a brush -->
<conv:NumericValueBrushColorConverter x:Key="NumericValueBrushColorConverter"></conv:NumericValueBrushColorConverter>
<Style x:Key="CurrencyStyle" TargetType="DataGridCell">
<Setter Property="HorizontalAlignment" Value="Right" />
<Setter Property="Foreground" Value="{Binding WhatGoesHere, Converter={StaticResource NumericValueBrushColorConverter}}"></Setter>
</Style>
</Window.Resources>
<DataGrid ItemsSource="{Binding CashReport}">
<DataGrid.Columns>
<DataGridTextColumn Header="Beginning Cash Available" Binding="{Binding BeginningBalance, StringFormat={}{0:C}}" CellStyle="{StaticResource CurrencyStyle}" />
<DataGridTextColumn Header="Ending Cash Available" Binding="{Binding EndingBalance, StringFormat={}{0:C}}" CellStyle="{StaticResource CurrencyStyle}" />
</DataGrid.Columns>
</DataGrid>
更新 #1
根据 Jefim 的建议,我应该尝试使用 ElementStyle,因为它直接在呈现的 TextBlock 上工作,而不是 (CellStyle) 包含 TextBlock 的内容控件(无论是什么)。
<Style x:Key="CurrencyStyle" TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Right" />
<Setter Property="Foreground" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Text, Converter={StaticResource NumericValueBrushColorConverter}}"/>
</Style>
<DataGrid ItemsSource="{Binding CashReport}">
<DataGrid.Columns>
<DataGridTextColumn Header="Beginning Cash Available" Binding="{Binding BeginningBalance, StringFormat={}{0:C}}" ElementStyle="{StaticResource CurrencyStyle}" />
<DataGridTextColumn Header="Ending Cash Available" Binding="{Binding EndingBalance, StringFormat={}{0:C}}" ElementStyle="{StaticResource CurrencyStyle}" />
</DataGrid.Columns>
</DataGrid>
这似乎有效,但是当我跟踪转换器的 Convert 方法时,它似乎触发了大约 28 次左右,并且将空值传递给 Convert 方法。之后,所有值都按预期流动。当网格渲染一切正常时,没有空单元格。什么会在前 20 多次没有值的情况下执行我的转换器?
更新 #2 我相信我当前的问题与原始问题无关,因此我将其移至:IValueConverter executes more times than expected
【问题讨论】:
标签: wpf wpfdatagrid