Den*_*gan 6 c# wpf listview itemssource
由于这是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>
Run Code Online (Sandbox Code Playgroud)
我有这个代码隐藏:
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!
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我将声明留下Hello.ItemSource = AllRoles注释,则网格不显示任何内容.当我把它放回去时,它会显示正确的东西.为什么是这样?
小智 15
这个:
<ListView ItemsSource="{Binding AllRoles}" Name="Hello">
Run Code Online (Sandbox Code Playgroud)
表示"绑定ItemsSource到属性this.DataContext.AllRoles",其中this是当前元素.
Hello.ItemsSource = AllRoles;
Run Code Online (Sandbox Code Playgroud)
意味着"绑定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;
}
}
Run Code Online (Sandbox Code Playgroud)
并在xaml
<ListView ItemsSource="{Binding}" Name="Hello">
Run Code Online (Sandbox Code Playgroud)
或者,或者,您可以使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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用RelativeSource告诉Binding将逻辑树向上走到Window
<ListView
ItemsSource="{Binding AllRoles, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"
Name="Hello">
Run Code Online (Sandbox Code Playgroud)
这意味着"查看我的祖先,直到找到一个窗口,然后在名为AllRoles的窗口上查找公共属性".
但是,最好的方法是完全跳过frigging代码隐藏并使用MVVM模式. 我建议你是否知道你直接跳到MVVM模式.学习曲线陡峭,但你学习了关于绑定和命令以及WPF的重要,很酷的事情.
| 归档时间: |
|
| 查看次数: |
19879 次 |
| 最近记录: |