簡體   English   中英

WPF獲取組合框項目模板的選定選項

[英]WPF Getting selected option of combobox item template

我通過數據模板用文本塊填充組合框,因為這是我可以找到的使用變量列表填充下拉框的最直接方法。 但是,由於我現在正在嘗試讀取值或選定的選項,所以我不知道如何解決它。 所有其他主題建議“ 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的第一行! 項目的屏幕截圖

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

SelectedItem投射到一個Person

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

為了使綁定( SelectedValue="{Binding dans}" )起作用, dans應該是ComboBoxDataContextstring屬性,並且還應該將SelectedValuePath屬性設置為“ dans”:

<ComboBox Name="DropdownDansen" ... SelectedValue="{Binding dans}" SelectedValuePath="dans">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM