带有单选按钮的WPF IValueConverter

w7t8yxp5  于 2023-04-13  发布在  其他
关注(0)|答案(1)|浏览(150)

我有一个数据网格,其中绑定了一个对象列表。每个对象都有一个Number属性。我有2个单选按钮,如果选中第一个,则默认值应显示在列中,但如果选中第二个单选按钮,我想将整个列除以1000。我尝试使用IValueConverter,但当我将Converter添加到DataGridTextColumn的Binding时,数字列是空的。2我不想改变对象的属性,只想在UI中改变。3我怎样才能做到这一点呢?
我试过的代码:

public class NumberConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is long numValue)
            return numValue / 1000.0;
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is long numValue)
            return numValue * 1000.0;
        return value;
    }
}

XAML代码:

<Window.Resources>
  <local:NumberConverter x:Key="NumberConverter"/>
</Window.Resources>

               <RadioButton 
                    Grid.Column="1"
                    HorizontalAlignment="Right"
                    x:Name="MultiplyBy1000" 
                    GroupName="chkFormat" 
                    Content="Default" 
                    IsChecked="{Binding IsDefaultChecked}"
                    Margin="5"/>

                <RadioButton 
                    Grid.Column="2"
                    HorizontalAlignment="Left"
                    x:Name="DivideBy1000"
                    GroupName="chkFormat" 
                    Content="Divide by 1000"
                    IsChecked="{Binding IsDivideNumChecked}"
                    Margin="5"/>

....

<DataGridTextColumn Header="Number" Width="0.7*" Binding="{Binding Number,Converter={StaticResource NumberConverter}"/>
fwzugrvs

fwzugrvs1#

您需要使用MultiValueConverter并绑定值和单选按钮的IsChecked值。
一个类似下面的值转换器:

public class ConditionalDividerConverter: IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var divide = (bool)values[0];
        var value = (double)values[1];
        return divide ? value / 1000 : value;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException("Not implemented");
    }
}

以及绑定的用法:

<DataGridTextColumn Header="Number" Width="0.7*" >
  <DataGridTextColumn.Binding>
    <MutliBinding Converter="{StaticResource conditionalDividerConverter}">
      <MultiBinding.Bindings>
        <Binding ElementName="DivideBy1000" Path="IsChecked" />
        <Binding Path="Number" />
      </MultiBinding.Bindings>
    </MultiBinding>
  </DataGridTextColumn.Binding>
</DataGridTextColumn>

相关问题