2017-08-09 53 views
0

如何獲取WPF中組合框的選定文本塊項目?如何獲取WPF中組合框的選定文本塊項目

這裏是我的代碼

<ComboBox Width="180" Name="comboBox"> 
       <ComboBoxItem> 
        <StackPanel Orientation="Horizontal"> 
         <Label Background="Red"></Label> 
         <TextBlock Width="150">Apple</TextBlock> 
         <Label ></Label> 
        </StackPanel> 
       </ComboBoxItem> 
</ComboBox> 

回答

0

針對您的特殊情況下,下面的代碼是可行的辦法之一,但要謹慎這種類型的代碼可能無法涵蓋所有​​可能出現的情況,例如,如果在佈局的變化模板等:

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    var item = (comboBox.SelectedItem as ComboBoxItem).Content as StackPanel; 
    TextBlock tbkValue = null; 
    if (item != null) 
    { 
     tbkValue = (item as StackPanel).Children.Cast<UIElement>().ToList().Where(it => it.GetType() == typeof(TextBlock)).Cast<TextBlock>().FirstOrDefault(); 
    } 
    if(tbkValue != null) 
    { 
     MessageBox.Show(tbkValue.Text); 
    } 
} 

相反,我建議WPF的強大的數據綁定的方法可以使用MVVM,只要有可能,這不僅緩解了大部分的複雜性和來回的數據更新,而且更清潔,維護當然單位t可靠的代碼也是如此。

希望這能爲您提供一些想法。

相關問題