2010-01-27 64 views
6

由於這是WPF,它可能看起來像很多代碼,但不要害怕,問題很簡單!WPF:在XAML中設置ItemSource與代碼隱藏

我有以下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,網格顯示什麼。當我把它放回去時,它顯示正確的東西。爲什麼是這樣?

回答

15

此:

<ListView ItemsSource="{Binding AllRoles}" Name="Hello"> 

意味着 「綁定ItemsSource到屬性this.DataContext.AllRoles」,其中this是當前元素。

Hello.ItemsSource = AllRoles; 

的意思是「綁定ItemsSourceObservableCollection<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來告訴綁定走上邏輯樹到窗口

<ListView 
    ItemsSource="{Binding AllRoles, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" 
    Name="Hello"> 

這意味着「看看我的祖先,直到找到一個窗口,然後在名爲AllRoles的窗口上查找公共屬性」。

但是最好的辦法是完全跳過嚴格的代碼隱藏,並使用MVVM pattern.如果你知道你直接跳到MVVM模式,我建議你這樣做。學習曲線非常陡峭,但您可以瞭解綁定和命令的所有信息,以及有關WPF的重要,酷炫的內容。