wpf 如何使用 XAML 中的选定值制作简单的组合框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1818756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:16:59  来源:igfitidea点击:

How to make simple combobox with selected value in XAML?

wpfxamlcomboboxselectedvalue

提问by Edward Tanguay

What is the correct syntax to select a combobox item with value(not index) in pure XAML?

在纯 XAML 中选择具有(不是索引)的组合框项的正确语法是什么?

Doesn't work:

不起作用:

<StackPanel>
    <ComboBox SelectedValue="CA">
        <ComboBoxItem Tag="CO">Colorado</ComboBoxItem>
        <ComboBoxItem Tag="CA">California</ComboBoxItem>
        <ComboBoxItem Tag="NM">New Mexico</ComboBoxItem>
    </ComboBox>
</StackPanel>

Doesn't work:

不起作用:

<StackPanel>
    <ComboBox SelectedValue="CA">
        <ComboBoxItem Value="CO">Colorado</ComboBoxItem>
        <ComboBoxItem Value="CA">California</ComboBoxItem>
        <ComboBoxItem Value="NM">New Mexico</ComboBoxItem>
    </ComboBox>
</StackPanel>

Even this doesn't work:

即使这不起作用:

<ComboBox SelectedValue="Colorado">
    <ComboBoxItem Tag="CO">Colorado</ComboBoxItem>
    <ComboBoxItem Tag="CA">California</ComboBoxItem>
    <ComboBoxItem Tag="NM">New Mexico</ComboBoxItem>
</ComboBox>

This doesn't work:

这不起作用:

<StackPanel>
    <ComboBox SelectedItem="CA">
        <ComboBoxItem Tag="CO">Colorado</ComboBoxItem>
        <ComboBoxItem Tag="CA">California</ComboBoxItem>
        <ComboBoxItem Tag="NM">New Mexico</ComboBoxItem>
    </ComboBox>
</StackPanel>

回答by martin

I think this should work. Have a try.

我认为这应该有效。试试。

<StackPanel>
    <ComboBox>
        <ComboBoxItem Tag="CO">Colorado</ComboBoxItem>
        <ComboBoxItem Tag="CA" IsSelected="True">California</ComboBoxItem>
        <ComboBoxItem Tag="NM">New Mexico</ComboBoxItem>
    </ComboBox>
</StackPanel>

回答by Dwsgg

<ComboBox SelectedValuePath="Content" SelectedValue="{Binding Source="...", Path="..."}">
   <ComboBoxItem Content="..." isSelected="true"/>
   <ComboBoxItem Content="..." />
   <ComboBoxItem Content="..." />
</ComboBox>

It should work with content, tag... or any other property you'd like to bind.

它应该适用于内容、标签...或您想要绑定的任何其他属性。

回答by Swapnil Karmalkar

<StackPanel>
    <ComboBox AllowDrop="True">
        <ComboBoxItem Tag="CO">Colorado</ComboBoxItem>
        <ComboBoxItem Tag="CA" IsSelected="True">California</ComboBoxItem>
        <ComboBoxItem Tag="NM">New Mexico</ComboBoxItem>
    </ComboBox>
</StackPanel>

You need to set AllowDrop="True" for the combobox and isselected for the item.

您需要为组合框设置 AllowDrop="True" 并为项目选择。

回答by Konamiman

The ComboBox element has a SelectedItemproperty, maybe this is the one you need.

ComboBox 元素有一个SelectedItem属性,也许这就是你需要的。