【问题标题】:WPF get selected Combobox value which is bound to observablecollectionWPF获取绑定到observablecollection的选定组合框值
【发布时间】:2020-10-14 07:08:53
【问题描述】:

我有一个绑定到ObservableCollectionComboBox(CBaddress)。

XAML

<ComboBox
   x:Name="CBaddress"
   Height="23"
   Margin="80,75,423,0"
   VerticalAlignment="Top" 
   ItemTemplate="{StaticResource AddressTemplate}"
   ItemsSource="{Binding}"
/>

<DataTemplate x:Key="AddressTemplate">
   <StackPanel Orientation="Horizontal">
      <TextBlock Width="50" Text="{Binding Path=ID_}" />
      <TextBlock Width="100" Text="{Binding Path=Address_}" />
      <TextBlock Width="30" Text="{Binding Path=HouseNumber_}" />
      <TextBlock Width="40" Text="{Binding Path=PostalCode_}" />
      <TextBlock Width="150" Text="{Binding Path=State_}" />
   </StackPanel>
</DataTemplate>

ObservableCollectionclass(地址)组成。

class Address
{
   public int ID_ { get; set; }
   public string Country_ { get; set; }
   public string State_ { get; set; }
   public int PostalCode_ { get; set; }
   public string Address_ { get; set; }
   public int HouseNumber_ { get; set; }
}

当我的程序启动时,它会从数据库中加载所有值,并可以在ComboBox 中完美显示所有值:

CBaddress.DataContext = database.SelectAllAddresses();

但是我如何获得这些值?使用CBaddress.Text 我只得到这个输出:

MySQL_WPF.classes.Address

是否可以得到纯文本,也显示在ComboBox中?

如果我能从选定的值中得到某个值,那就最好了,比如ID_

【问题讨论】:

  • ComboBox 中应该显示哪个属性?您所说的“我如何获得价值?”是什么意思?你想获取哪些值,选中的项,所有的项?
  • XAML DataTemplate 中显示的属性,没关系。我的问题是,我如何使用选定的值。喜欢是否可以只获取所选值的 ID_

标签: c# wpf class combobox observablecollection


【解决方案1】:

如果您想获取所选项目,请使用ComboBox 上的SelectedItem 属性访问它。

var selectedID = ((Address)CBaddress.SelectedItem).ID_ ;

SelectedItem 属性的类型为object,因此您需要将其转换为您的数据类型Address。然后你就可以像往常一样访问它的任何属性了。

如果您在 MVVM 场景中工作,您可以将 SelectedItem 绑定到视图模型上的属性,例如SelectedAddress.

<ComboBox ...
          ItemsSource="{Binding}"
          SelectedItem={Binding SelectedAddress}"/>
private Address _selectedAddress;
public Address SelectedAddress
{
   get => _selectedAddress;
   set
   {
      if (_selectedAddress == value)
         return;

      _selectedAddress = value;
      OnPropertyChanged();
   }
}

然后您可以以相同的方式访问任何属性,例如:

var selectedID = SelectedAddress.ID_;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-03
    • 2018-12-20
    • 1970-01-01
    • 2013-10-27
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多