WPF 获取绑定到 observablecollection 的选定 Combobox 值

WPF get selected Combobox value which is bound to observablecollection

我有一个 ComboBox (CBaddress) 绑定到 ObservableCollection.

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>

ObservableCollection由一个class(地址)组成。

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 上使用 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_;