2017-08-09 67 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可靠的代码也是如此。

希望这能为您提供一些想法。

相关问题