我有一个DataGridTextColumn,它接受名为Numbers的数据库表中的数字。如果单元格中的数字是正数,那么我希望下一个DataGridTextColumn中包含单词“Positive”。我试过IConverter样式,但仍然不知道该怎么做。我希望有人可以帮助我。
到目前为止,这是我的代码:
<DataGrid Grid.Row="0" Grid.Column="1" AutoGenerateColumns="False" IsReadOnly="false" CanUserAddRows="True" Margin="5,5,10,5" ItemsSource="{Binding ElementName=Numbers}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Num}" Header="Number" FontSize="16"/>
<DataGridTextColumn Header="Positive/Negative" FontSize="16">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Text" Value="{Binding Amount, Converter={StaticResource PositiveNegativeConverter}}"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid>
我在内部资源中也有这个:
<local:PositiveNegativeConverter x:Key="PositiveNegativeConverter"/>
</UserControl.Resources>
我的转换器看起来像这样:
class PositiveNegativeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool revert = (parameter as string).StartsWith("-");
string stringValue = value as string;
string compareValue = parameter as string;
if (revert)
{
return "Negative";
}
else
return "Positive";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
答案 0 :(得分:3)
您不必为此添加样式,只需将转换器添加到DataGridTextColumn中的Binding。
这样的事情:
<DataGridTextColumn Binding="{Binding Num, Converter={StaticResource PositiveNegativeConverter}}" Header="Number" FontSize="16"/>