由于这是WPF,它可能看起来像很多代码,但不要害怕,问题很简单!
我有以下XAML:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:hax="clr-namespace:hax" x:Class="hax.MainWindow"
x:Name="Window" Title="Haxalot" Width="640" Height="280">
<Grid x:Name="LayoutRoot">
<ListView ItemsSource="{Binding AllRoles}" Name="Hello">
<ListView.View>
<GridView>
<GridViewColumn Header="Name"
DisplayMemberBinding="{Binding Path=FullName}"/>
<GridViewColumn Header="Role"
DisplayMemberBinding="{Binding Path=RoleDescription}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
我有这个代码隐藏:
using System.Collections.ObjectModel;
using System.Windows;
namespace hax
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<Role> AllRoles { get { return m_AllRoles; } set { m_AllRoles = value; } }
private ObservableCollection<Role> m_AllRoles = new ObservableCollection<Role>();
public MainWindow()
{
this.InitializeComponent();
AllRoles.Add(new Role("John", "Manager"));
AllRoles.Add(new Role("Anne", "Trainee"));
// Hello.ItemsSource = AllRoles; // NOTE THIS ONE!
}
}
}
如果我将语句Hello.ItemSource = AllRoles
注释掉,则网格显示 nothing 。当我把它放回去时,它会显示正确的东西。这是为什么?
答案 0 :(得分:15)
此:
<ListView ItemsSource="{Binding AllRoles}" Name="Hello">
表示“将ItemsSource
绑定到属性this.DataContext.AllRoles
”,其中this
是当前元素。
Hello.ItemsSource = AllRoles;
表示“将ItemsSource
绑定到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">
OR,或者,你可以让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的窗口上寻找一个公共属性”。
但是,最好的方法是完全跳过frigging代码隐藏,并使用我建议的MVVM pattern.,如果你知道你直接跳到MVVM模式。学习曲线陡峭,但你学习了关于绑定和命令以及WPF的重要,很酷的事情。
答案 1 :(得分:0)
当您绑定到WPF中的数据源时,它正在查找名为“AllRoles”的Window的数据上下文的属性。有关xaml中数据绑定的更多信息,请查看Model-View-ViewModel模式。 http://msdn.microsoft.com/en-us/magazine/dd419663.aspx