开发者

Setting the SelectedItem for ComboBox component in WPF

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()
{
    cbProductDefaultVatRa开发者_运维技巧te.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!


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜