[英]WPF get selected Combobox value which is bound to observablecollection
I have a ComboBox
(CBaddress) which is bound to an ObservableCollection
.我有一个绑定到ObservableCollection
的ComboBox
(CBaddress)。
XAML 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>
The ObservableCollection
consists of a class
(Address). 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; }
}
When my program starts it loads all values from a database and can display all values perfectly in the ComboBox
:当我的程序启动时,它会从数据库中加载所有值,并且可以在ComboBox
完美显示所有值:
CBaddress.DataContext = database.SelectAllAddresses();
But how do I get the values?但是我如何获得这些值? With CBaddress.Text
I get only this output :使用CBaddress.Text
我只得到这个输出:
MySQL_WPF.classes.Address MySQL_WPF.classes.Address
Is it possible to get the plain text, which is also displayed in the ComboBox
?是否可以获取也显示在ComboBox
的纯文本?
It would be best if I could get a certain value from the selected value, like the ID_
.如果我能从选定的值中获得某个值,比如ID_
,那将是最好的。
If you want to get the selected item, access it with the SelectedItem
property on ComboBox
.如果要获取所选项目,请使用ComboBox
上的SelectedItem
属性访问它。
var selectedID = ((Address)CBaddress.SelectedItem).ID_ ;
The SelectedItem
property is of type object
, so you need to cast it to your data type Address
. SelectedItem
属性属于object
类型,因此您需要将其强制转换为您的数据类型Address
。 Then you can access any of its properties as usual.然后您可以像往常一样访问它的任何属性。
If you are working in an MVVM scenario, you would bind the SelectedItem
to a property on your view model, eg SelectedAddress
.如果您在 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();
}
}
Then you could access any property the same way, eg:然后您可以以相同的方式访问任何属性,例如:
var selectedID = SelectedAddress.ID_;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.