簡體   English   中英

ComboBox SelectedItem 未顯示其值

[英]ComboBox SelectedItem is not showing its value

我有一個ComboBox ,它的ComboBoxItem都是在運行時(以編程方式)生成的。 每當出現ComboBox.SelectionChange時,程序將顯示一個MessageBox ,顯示ComboBox的選定內容

private void cb2_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show(cb2.SelectedItem.ToString());
}

但是,它向我展示:

System.Windows.Controls.ComboBoxItem:Hello World

我只想顯示“Hello World”而不是“System....”的東西。 我嘗試了 SelectedValue,這也顯示了同樣的情況。

您需要將所選項目轉換為 ComboBoxItem 並僅獲取其內容。

MessageBox.Show((cb2.SelectedItem as ComboBoxItem).Content.ToString());

您應該考慮使用綁定而不是事件處理程序。 這會導致代碼更簡潔,並在表示和流程之間更好地分離關注點:

如下聲明你的組合:

<ComboBox x:Name="cboCountries" DisplayMemberPath="Name" SelectedItem="{Binding SelectedCountry}" ItemsSource="{Binding Countries}" />

然后,您將 ComboBox 綁定到 Window(或者最好是 ViewModel)上的集合:

public Window1()
{
    InitializeComponent();

    DataContext = this;

    this.Countries = new ObservableCollection<Country>();
    this.Countries.Add(new Country {Id = 1, Name = "United Kingdom" });
    this.Countries.Add(new Country {Id = 1, Name = "United States" });
}

public ObservableCollection<Country> Countries {get; set;}

private Country selectedCountry;

public Country SelectedCountry
{
    get { return this.selectedCountry; }
    set 
    {
        System.Diagnostics.Debug.WriteLine(string.Format("Selection Changed {0}", value.Name));
        this.selectedCountry = value;
    }
}

Combo 的 SelectedValue 屬性上的綁定表達式將導致 SelectedCountry 上的屬性設置器在組合中的選定項更改時觸發。

public class Country
{
    public int Id { get; set;}

    public string Name {get; set;}
}

暫無
暫無

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

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