当我选择一个元素时,我有一个带有 DataTemplate 的组合框,只是所选元素的名称显示为选中。我该怎么做才能使所选元素的名称显示在选择中,如打开的组合框所示。
组合框的 XAML:
<ComboBox
ItemsSource="{Binding}"
Margin="51,146,238,146"
BorderThickness="0"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch"
Padding="3" Height="20" IsEditable="True"
SelectedValuePath="Name"
x:Name="testCombobox" SelectionChanged="testCombobox_SelectionChanged">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBox
Text="{Binding Path=Name}"
Padding="1,1,1,1"
AcceptsReturn="True"
Background="Yellow">
</TextBox>
</DataTemplate>
</ComboBox.ItemTemplate>
主窗口中的代码:
public partial class MainWindow : Window
{
ObservableCollection<Person> personen = new ObservableCollection<Person>();
public MainWindow()
{
InitializeComponent();
//testCombobox.ItemsSource = LoadComboBoxData;
personen.Add(new Person("Meier dsg dsfg sdgf sdfg sdfg", 67));
personen.Add(new Person("Fischer sdfgs sdfg sg sgssg sf", 23));
personen.Add(new Person("Schmidt sdfg sdfg sgf sfdg sf sdfqwe qwer qwe", 45));
personen.Add(new Person("Serna asdfd sdf dsf sdf sdf dsf dfa qwer qwe", 26));
personen.Add(new Person("Müller asdf a aafd aff dfda adf asdf qwer qwer ", 39));
this.DataContext = personen;
}
班级人:
public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, e);
}
private string _Name;
private int _Alter;
public Person(string name, int alter)
{
Name = name;
Alter = alter;
}
public int Alter
{
get { return _Alter; }
set
{
_Alter = value;
OnPropertyChanged(new PropertyChangedEventArgs("Alter"));
}
}
public string Name
{
get { return _Name; }
set
{
_Name = value;
OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
}