【发布时间】:2018-03-29 10:02:00
【问题描述】:
我有一个简单的 wpf 项目,它由一个包含员工 ObservableCollection 的列表框和 3 个文本框组成。
我还创建了一个“模型”类,它将像 Employee 这样的属性对象链接到 MainWindow。 Employee 类的属性称为“CurrentEmployee”。
我将一个模型对象初始化为窗口并将其命名为“boundModel”。当列表框上的选择发生更改时,我希望“boundModel.CurrentEmployee”更改为选择的任何员工,并且 3 个文本框也更改为员工的属性。我目前将“boundModel.CurrentEmployee”设置为列表框中选择的任何名称。当列表框选择发生变化时,boundModel.CurrentEmployee 也会发生变化!不幸的是,它不会在 MainWindow 上更新!
我想将 boundModel.CurrentEmployee 绑定到 3 个文本框。我想这样做,这样当我创建另一个类时,我可以通过 Model 类将该类链接到更多的 UI 控件。这是否可能,或者以任何方式有效?我的窗体背景在这里似乎几乎没用!
提前致谢!
主窗口后端
public partial class MainWindow : Window
{
Model boundModel;
public MainWindow()
{
boundModel = new Model();
InitializeComponent();
this.DataContext = boundModel;
lb_Employees.ItemsSource = boundModel.EmployeeCollection;
}
private void lb_Employees_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
boundModel.CurrentEmployee = (Employee)lb_Employees.SelectedItem;
}
}
XAML 主窗口
<ListBox x:Name="lb_Employees" SelectionChanged="lb_Employees_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBox x:Name="tb_Name" Text="{Binding boundModel.Name}"/>
<TextBox x:Name="tb_Age" Text="{Binding Age}"/>
<TextBox x:Name="tb_Kids" Text="{Binding HasKids}"/>
员工
class Employee : System.ComponentModel.INotifyPropertyChanged
{
private string name;
private int age;
private bool hasKids;
public string Name
{
get{return name;}
set
{
name = value;
Notify("Name");
}
}
public int Age
{
get{return age;}
set
{
age = value;
Notify("Age");
}
}
public bool HasKids
{
get{return hasKids;}
set
{
hasKids = value;
Notify("HasKids");
}
}
public Employee(string name, int age, bool haskids)
{
this.Name = name;
this.Age = age;
this.HasKids = haskids;
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
private void Notify(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this,
new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
型号
class Model : System.ComponentModel.INotifyPropertyChanged
{
public ObservableCollection<Employee> EmployeeCollection = new ObservableCollection<Employee>();
private Employee currentemployee;
public Employee CurrentEmployee
{
get {return currentemployee;}
set
{
currentemployee = value;
Notify("Employee");
}
}
public Model()
{
EmployeeCollection.Add(new Employee("Tom Smith", 40, true));
EmployeeCollection.Add(new Employee("Beth Smith", 38, true));
EmployeeCollection.Add(new Employee("Steph Rodriguez", 25, false));
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
private void Notify(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this,
new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
【问题讨论】:
标签: c# wpf xaml data-binding listbox