在WPF中,如果您想要获取ComboBox中的数据项的属性值,您可以使用以下方法:
以下是一个简单的示例:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox x:Name="MyComboBox" SelectionChanged="MyComboBox_SelectionChanged" Margin="5">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Width="100"/>
<TextBlock Text="{Binding Age}" Width="50"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Window>
using System.Windows;
using System.Collections.ObjectModel;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public ObservableCollection<Person> Persons { get; set; }
public MainWindow()
{
InitializeComponent();
Persons = new ObservableCollection<Person>
{
new Person { Name = "张三", Age = 25 },
new Person { Name = "李四", Age = 30 },
new Person { Name = "王五", Age = 35 },
};
MyComboBox.ItemsSource = Persons;
}
private void MyComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedItem = MyComboBox.SelectedItem as Person;
if (selectedItem != null)
{
string name = selectedItem.Name;
int age = selectedItem.Age;
// 处理选中项的属性值
MessageBox.Show($"选中的人的姓名为:{name},年龄为:{age}");
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}
在这个示例中,我们有一个包含Name和Age属性的Person类。我们创建了一个Person对象集合,并将其设置为ComboBox的数据源。我们为ComboBox添加了一个SelectionChanged事件处理程序,当用户选择一个项时,这个事件处理程序会被触发。
在处理程序中,我们将SelectedItem属性转换为Person对象,并访问其Name和Age属性。
领取专属 10元无门槛券
手把手带您无忧上云