views:

48

answers:

2

XAML:

<ComboBox Height="27" Margin="124,0,30,116" Name="cbProductDefaultVatRate" VerticalAlignment="Bottom" ItemsSource="{Binding}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Label Height="26" Content="{Binding Path=Value}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Set Data for cbProductDefaultVatRate.Items (Type - VatRate):

private void ShowAllVatRates()
{
    cbProductDefaultVatRate.Items.Clear();
    cbProductDefaultVatRate.ItemsSource = new VatRateRepository().GetAll();
}

Similarly, I defined property:

private Product SelectedProduct
{
    get; set;
}

The Product contains VatRate:

SelectedProduct.DefaultVatRate

How to set SelectedItem equal SelectedProduct.DefaultVatRate? I tried:

cbProductDefaultVatRate.SelectedItem = SelectedProduct.DefaultVatRate;

But it does not work.

Thank you for answers!

A: 

Are you looking to get a TwoWay binding like this?

    <ComboBox Height="27" Margin="124,0,30,116" Name="cbProductDefaultVatRate" VerticalAlignment="Bottom" 
ItemsSource="{Binding}" 
SelectedItem="{Binding SelectedProduct.DefaultVatRate, Mode=TwoWay}>
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <Label Height="26" Content="{Binding Path=Value}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
Dan Bryant
`SelectedItem` is TwoWay bound by default (BindsTwoWayByDefault). So you don't need to explitly redefine that in the xaml binding expression.
bitbonk
@bitbonk, Thanks, I never knew that.
Dan Bryant
+1  A: 

You need to make sure that the actual object instance behind SelectedProduct.DefaultVatRate is the same instance as the one that is part of the list returned by new VatRateRepository().GetAll() or object.Equals() must return true for the two instances.

bitbonk
Thanks for the tip! While I write as follows:foreach (var item in cbProductDefaultVatRate.Items){ if (Equals(((VatRate)item).Value, SelectedProduct.DefaultVatRate.Value)) cbProductDefaultVatRate.SelectedItem = item;}
Anry