This:
<ListView ItemsSource="{Binding AllRoles}" Name="Hello">
意思是“绑定ItemsSource
到酒店this.DataContext.AllRoles
" where this
是当前元素。
Hello.ItemsSource = AllRoles;
意思是“绑定ItemsSource
to an ObservableCollection<T>
充满角色”,它直接做你最初想做的事情。
在 xaml 中有多种方法可以实现此目的。这是一个:
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
var allRoles = new ObservableCollection<Role>()
allRoles.Add(new Role("John", "Manager"));
allRoles.Add(new Role("Anne", "Trainee"));
this.DataContext = allRoles;
}
}
并在xaml中
<ListView ItemsSource="{Binding}" Name="Hello">
或者,或者,您可以将 AllRoles 设为窗口的公共属性
public partial class MainWindow : Window
{
public ObservableCollection<Role> AllRoles {get;private set;}
public MainWindow()
{
this.InitializeComponent();
var allRoles = new ObservableCollection<Role>()
allRoles.Add(new Role("John", "Manager"));
allRoles.Add(new Role("Anne", "Trainee"));
this.AllRoles = allRoles;
}
}
然后使用RelativeSource告诉Binding沿着逻辑树向上走到Window
<ListView
ItemsSource="{Binding AllRoles, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"
Name="Hello">
这意味着“查看我的祖先,直到找到一个窗口,然后在该窗口上查找名为 AllRoles 的公共属性”。
但最好的方法是完全跳过该死的代码隐藏并使用MVVM 模式。如果您正在学习,我建议您直接跳到 MVVM 模式。学习曲线很陡峭,但您可以了解有关绑定和命令的所有内容以及有关 WPF 的重要、酷炫的内容。