WPF获取组合框项目模板的选定选项

时间:2018-10-26 14:40:35

标签: c# wpf combobox dropdown itemtemplate

我通过数据模板用文本块填充组合框,因为这是我可以找到的使用变量列表填充下拉框的最直接方法。 但是,由于我现在正在尝试读取值或选定的选项,所以我不知道如何解决它。 所有其他主题建议“ SelectedValue.ToString();”之类的内容,但这只会返回我的XAML的第一行。

我的Xaml;

<ComboBox Name="DropdownDansen" Grid.Column="1" Grid.Row="2" Margin="5" 
Grid.ColumnSpan="2" SelectedValue="{Binding dans}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding dans}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

我的CS:

    public List<Person> people = new List<Person>();

        public MainWindow()
        {
            InitializeComponent();
            people.Add(new Person { id = "0", dans = "Tango", teamlid1 = "Daniel 
", teamlid2 = "Sabrina ", coach = "Hans van Bommel" });
            people.Add(new Person { id = "1", dans = "Wals", teamlid1 = "de Ridder", teamlid2 = "Aninka ", coach = "Hans van Bommel" });
            people.Add(new Person { id = "2", dans = "Foxtrot", teamlid1 = "de Ridder", teamlid2 = "de Ridder", coach = "Hans van Bommel" });
            people.Add(new Person { id = "3", dans = "Quickstep", teamlid1 = "de Ridder", teamlid2 = "de Ridder", coach = "Dansschool van Amersfoort" });

            DropdownDansen.ItemsSource = people;
            displayDans.DataContext = new DisplayText() { deDans = "chachacha" 
    };
            displaylid1.DataContext = new DisplayText() { lid1 = "Kees" };
            displaylid2.DataContext = new DisplayText() { lid2 = "Hariette" };
            displaycoach.DataContext = new DisplayText() { deCoach = "Steve" };
        }

        public class Person
        {
            public string id { get; set; }
            public string dans { get; set; }
            public string teamlid1 { get; set; }
            public string teamlid2 { get; set; }
            public string coach { get; set; }

        }

编辑: @ mm8提供的答案很有效! 但是,在组合框更新后,下拉菜单中填充了我的xaml的第一行! screenshot of project

 <ComboBox Name="DropdownDansen" Grid.Column="1" Grid.Row="2" Margin="5" Grid.ColumnSpan="2" SelectedValue="{Binding dans}" SelectedValuePath="dans"/>

1 个答案:

答案 0 :(得分:2)

SelectedItem投射到Person

Person selectedPerson = DropdownDansen.SelectedItem as Person;
if (selectedPerson != null)
{
    string dans = selectedPerson.dans;
}

为使绑定(SelectedValue="{Binding dans}")有效,dans应该是string的{​​{1}}的{​​{1}}属性,并且还应该设置将DataContext属性设置为“ dans”:

ComboBox