1

I have been defined some ComboBox element:

<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>

and set the data source for component items of VatRate type:

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

VatRate object has a property:

private Product SelectedProduct
{
    get; set;
}

where is a product contains VatRate as well:

SelectedProduct.DefaultVatRate

How to set SelectedItem property of ComboBox to SelectedProduct.DefaultVatRate?

// does not work!!!
cbProductDefaultVatRate.SelectedItem = SelectedProduct.DefaultVatRate;

Thank you for answers!

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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; }
1

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>

1 Comment

SelectedItem is TwoWay bound by default (BindsTwoWayByDefault). So you don't need to explitly redefine that in the xaml binding expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.