1 回答
TA贡献1824条经验 获得超6个赞
您可以使用包含模型的 List 并绑定到组合框项目源,并且可以绑定 DisplayMemberPath 来表示“Name”(模型的属性)并将 SelectedItem 绑定到该模型。
请看代码。我使用了虚拟字符串值。在您的情况下,这应该是从数据库填充的,正如您提到的。请注意,在 SelectedEmployee 的设置器中,我根据您的要求为 NumText 分配值。一旦选定的项目发生更改,它将被分配并显示在 XAML 文本框中
在您的情况下,您错误地将 SelectedItem 分配给 list 。它应该与您绑定的itemsource相关。您创建了单独的列表,一个用于项目源,另一个用于所选项目。而且我在代码中看不到与 INotifyPropertyChanged 相关的属性设置器的任何更改。
XAML:
<Window x:Class="WpfApplication13.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication13"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50*"/>
<RowDefinition Height="50*"/>
</Grid.RowDefinitions>
<TextBox x:Name="text_nume" HorizontalAlignment="Center" Height="23" TextWrapping="Wrap" Text="{Binding NumeText}" VerticalAlignment="Center" Width="89" Grid.Row="0" />
<ComboBox x:Name="comboPersonal" Grid.Row="1" Height="30" Width="100" HorizontalAlignment="Center" DisplayMemberPath="Name" VerticalAlignment="Center" Margin="13,60,-62,0" ItemsSource="{Binding Ang1}" SelectedItem="{Binding SelectedEmployee}" />
</Grid>
</Window>
视图模型:
public class ViewModel : INotifyPropertyChanged
{
#region Constants and Enums
#endregion
#region Private and Protected Member Variables
private IList<EmployeeModel> ang1;
EmployeeModel _selectedEmployee;
private string numeText;
#endregion
#region Private and Protected Methods
private void OnPropertyChanged(string propName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
#endregion
#region Constructors
public ViewModel()
{
Ang1 = new List<EmployeeModel>();
Ang1.Add(new EmployeeModel() { Name="1"});
Ang1.Add(new EmployeeModel() { Name = "2" });
}
#endregion
#region Public Properties
public IList<EmployeeModel> Ang1
{
get
{
return ang1;
}
set
{
ang1 = value;
OnPropertyChanged(nameof(Ang1));
}
}
public EmployeeModel SelectedEmployee
{
get
{
return _selectedEmployee;
}
set
{
_selectedEmployee = value;
NumeText = value.Name;
OnPropertyChanged(nameof(SelectedEmployee));
}
}
public string NumeText
{
get
{
return this.numeText;
}
set
{
this.numeText = value;
OnPropertyChanged(nameof(NumeText));
}
}
#endregion
#region Public Methods
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
模型:
public class EmployeeModel
{
public string Name { get; set; }
}
我使用 INotifyPropertyChanged 来绑定通知。让我知道这是否有帮助
- 1 回答
- 0 关注
- 126 浏览
添加回答
举报