Vahid
Vahid

Reputation: 5444

How to define a value converter for a combobox in XAML

I'm trying to load the values of the DistanceRoundoffs List into a ComboBox. The values are in mm but I want to display them in cm so I'll need to use a value converter.

I don't know how and where to use it. Should I define it in ItemsSource or SelectedItem?

I don't need the code for value converter; Just the implementation in XAML for the current combobox.

<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");
    }
}

Upvotes: 1

Views: 521

Answers (1)

Clemens
Clemens

Reputation: 128060

You should use the converter in the ItemTemplate of the ComboBox:

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

Upvotes: 3

Related Questions