WPF datagrid:converter和StringFormat

时间:2012-05-29 09:07:22

标签: c# wpf .net-3.5

我有一个标准(WPF工具包)数据网格。一些列(明确定义)必须以百分比显示。如果值低于0,则某些列必须以红色显示。(两组列不相同)。我尝试分别使用StringFormatStyle来实现这些要求。我的XAML:

<Window xmlns:local="clr-namespace:myNamespace"
        xmlns:tk="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit">
    <Window.Resources>
        <local:ValueConverter x:Key="valueToForeground" />
        <Style TargetType="{x:Type tk:DataGridCell}">
            <Setter Property="Foreground"
                    Value="{Binding RelativeSource={RelativeSource Self}, Path=Content.Text, Converter={StaticResource valueToForeground}}" />
        </Style>
    </Window.Resources>
    <Grid>
        <tk:DataGrid AutoGenerateColumns="False"
                     ItemsSource="{Binding Path=myClass/myProperty}">
            <tk:DataGrid.Columns>
                <tk:DataGridTextColumn Header="A"
                                       Binding="{Binding colA}" />
                <tk:DataGridTextColumn Header="B"
                                       Binding="{Binding colB, StringFormat=\{0:P\}}" />
                <tk:DataGridTextColumn Header="C"
                                       Binding="{Binding colC, StringFormat=\{0:P\}}" />
                <tk:DataGridTextColumn Header="D"
                                       Binding="{Binding colD, StringFormat=\{0:P\}}" />
            </tk:DataGrid.Columns>
        </tk:DataGrid>
    </Grid>
</Window>

相关的转换器:

namespace myNamespace
{
    public class ValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            SolidColorBrush brush = new SolidColorBrush(Colors.Black);

            Double doubleValue = 0.0;
            if (value != null)
            {
                if (Double.TryParse(value.ToString(), out doubleValue))
                {
                    if (doubleValue < 0)
                        brush = new SolidColorBrush(Colors.Red);
                }
            }
            return brush;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

我认为这一切都非常标准,但问题是转换器在经过Text后得到StringFormat值,此时很难正确解析它(因为实际上) ,并非所有列都具有相同的格式)。如果我取出StringFormats,转换器工作正常,文本显示为红色。我错过了一些明显的东西吗有一种简单的方法可以解决这个问题吗?我现在唯一能想到的就是将格式转移到另一个转换器中,我不相信它会起作用。

3 个答案:

答案 0 :(得分:6)

我们遇到类似情况,我们需要Path的不同Binding属性,但每个CellStyle需要类似的DataGridColumn。我们使用自定义MarkupExtension解决了这个问题。在你的情况下,它看起来像这样

<tk:DataGrid AutoGenerateColumns="False" 
                ItemsSource="{Binding MyItems}">
    <tk:DataGrid.Columns>
        <tk:DataGridTextColumn Header="A" 
                               Binding="{Binding colA}" />
        <tk:DataGridTextColumn Header="B" 
                               Binding="{Binding colB, StringFormat=\{0:P\}}"
                               CellStyle="{markup:ForegroundCellStyle PropertyName=colB}"/>
        <tk:DataGridTextColumn Header="C" 
                               Binding="{Binding colC, StringFormat=\{0:P\}}"
                               CellStyle="{markup:ForegroundCellStyle PropertyName=colC}"/>
        <tk:DataGridTextColumn Header="D" 
                               Binding="{Binding colD, StringFormat=\{0:P\}}"
                               CellStyle="{markup:ForegroundCellStyle PropertyName=colD}"/>
    </tk:DataGrid.Columns>
</tk:DataGrid>

然后ForegroundCellStyleExtensionStyle创建DataGridCell,具体取决于PropertyName

ForegroundCellStyleExtension

public class ForegroundCellStyleExtension : MarkupExtension
{
    public ForegroundCellStyleExtension() { }
    public ForegroundCellStyleExtension(string propertyName)
    {
        PropertyName = propertyName;
    }

    public string PropertyName
    {
        get;
        set;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        IProvideValueTarget service = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
        DependencyObject targetObject = service.TargetObject as DependencyObject;
        if (targetObject == null)
        {
            return null;
        }

        Binding foregroundBinding = new Binding
        {
            Path = new PropertyPath(PropertyName),
            Converter = new ValueConverter()
        };
        Style foregroundCellStyle = new Style(typeof(DataGridCell));
        foregroundCellStyle.Setters.Add(new Setter(DataGridCell.ForegroundProperty, foregroundBinding));

        return foregroundCellStyle;
    }
}

此外,如果您还想使用其他Setters等,则可以将其他参数包含在MarkupExtension中。

<Window.Resources>
    <Style x:Key="dataGridCellStyle" TargetType="{x:Type tk:DataGridCell}">
        <Setter Property="Background" Value="Blue"/>
    </Style>
</Window.Resources>
<!-- ... -->
<tk:DataGridTextColumn Header="B" 
                       Binding="{Binding colB, StringFormat=\{0:P\}}"
                       CellStyle="{markup:ForegroundCellStyle colB, {StaticResource dataGridCellStyle}}"/>

然后ForegroundCellStyleExtension会将第二个参数用作BasedOn DataGridCell的{​​{1}}

带有Style

ForegroundCellStyleExtension

BasedOn

答案 1 :(得分:2)

为每列指定单元格样式,如下所示:

<DataGridTextColumn Header="ColA" Binding="{Binding colA, StringFormat=\{0:P\}}">
    <DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="Foreground" 
                    Value="{Binding colA, Converter={StaticResource valueToForeground}}" />
         </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>

<DataGridTextColumn Header="ColB" Binding="{Binding colB, StringFormat=\{0:P\}}">
    <DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="Foreground" 
                    Value="{Binding colB, Converter={StaticResource valueToForeground}}" />
         </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>

... 

并修改您的转换器

public class ValueConverter : IValueConverter
{
    public object Convert(
                object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((double) value < 0) ? Brushes.Red : Brushes.Black;
    }

    public object ConvertBack(
                object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Binding.DoNothing;
    }
}

enter image description here

答案 2 :(得分:1)

我想到的最简单的方法是将您的完整项目而不是item / content.text仅绑定到您的转换器。然后,您将能够对您的单元格执行您需要担心的项目和参数值。

在你的手柄样式中:

 <Setter Property="Foreground"
     Value="{Binding Converter={StaticResource valueToForeground}}" />

并在您的转换器代码中:

public object Convert(object value, Type targetType,
    object parameter, System.Globalization.CultureInfo culture)
{
    SolidColorBrush brush = new SolidColorBrush(Colors.Black);    

    Double doubleValue = 0.0;
    if (value != null)
    {
        mydatatype data = value as mydatatype;
        //your logic goes here and also can play here with your dataitem. 
        if (Double.TryParse(data.CollD.ToString(), out doubleValue))
        {
            if (doubleValue < 0)
               brush = new SolidColorBrush(Colors.Red);
        }        
    }
    return brush;
}