【问题标题】:Setting the SelectedItem for ComboBox component in WPF在 WPF 中为 ComboBox 组件设置 SelectedItem
【发布时间】:2011-02-23 08:27:50
【问题描述】:

我已经定义了一些ComboBox元素:

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

并为VatRate类型的组件项设置数据源:

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

VatRate 对象有一个属性:

private Product SelectedProduct
{
    get; set;
}

产品在哪里也包含VatRate:

SelectedProduct.DefaultVatRate

如何将ComboBox的SelectedItem属性设置为SelectedProduct.DefaultVatRate?

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

感谢您的回答!

【问题讨论】:

    标签: c# wpf data-binding combobox selecteditem


    【解决方案1】:

    您是否希望获得这样的双向绑定?

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

    【讨论】:

    • SelectedItem 默认为双向绑定 (BindsTwoWayByDefault)。所以你不需要在 xaml 绑定表达式中明确地重新定义它。
    • @bitbonk,谢谢,我从来不知道。
    【解决方案2】:

    您需要确保SelectedProduct.DefaultVatRate 后面的实际对象实例与new VatRateRepository().GetAll() 或object.Equals() 返回的列表中的实例相同,这两个实例必须返回true。

    【讨论】:

    • 感谢您的提示!虽然我写如下: foreach (var item in cbProductDefaultVatRate.Items) { if (Equals(((VatRate)item).Value, SelectedProduct.DefaultVatRate.Value)) cbProductDefaultVatRate.SelectedItem = item; }
    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 2011-03-27
    • 2014-05-30
    • 2011-01-10
    • 2016-06-15
    • 2011-01-15
    • 2012-06-19
    • 1970-01-01
    相关资源
    最近更新 更多