如何在 XAML 中为组合框定义值转换器

How to define a value converter for a combobox in XAML

我正在尝试将 DistanceRoundoffs 列表的值加载到 ComboBox 中。这些值在 mm 中,但我想在 cm 中显示它们,所以我需要使用值转换器。

我不知道如何以及在哪里使用它。我应该在 ItemsSourceSelectedItem 中定义它吗?

我不需要值转换器的代码;只是 XAML 中当前组合框的实现。

<ComboBox ItemsSource="{Binding Path=DistanceRoundoffs}"
          SelectedItem="{Binding DistanceRoundoff, 
                    RelativeSource={RelativeSource FindAncestor, AncestorType=Window}, 
                    Mode=TwoWay}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock>
                    <TextBlock.Text>
                        <MultiBinding Converter="{StaticResource MultiUnitConverter}" ConverterParameter="{x:Static enumerations:Quantity.Length}">
                            <Binding Path="RebarsVerticalDistanceRoundoff"/>
                            <Binding Path="CurrentTargetUnit"/>
                        </MultiBinding>
                    </TextBlock.Text>
                </TextBlock>
            </DataTemplate>
        </ComboBox.ItemTemplate>
</ComboBox>

private List<double> distanceRoundoffs = new List<double> {25, 50};
public List<double> DistanceRoundoffs
{
    get { return distanceRoundoffs; }
    set
    {
        distanceRoundoffs = value;
        RaisePropertyChanged("DistanceRoundoffs");
    }
}

private double distanceRoundoff;
public double DistanceRoundoff
{
    get { return distanceRoundoff; }
    private set
    {
        distanceRoundoff= value;
        RaisePropertyChanged("DistanceRoundoff");
    }
}

您应该在 ComboBox 的 ItemTemplate 中使用转换器:

<ComboBox ...>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Converter={StaticResource UnitConverter}}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>