2009-01-15 235 views
1

我想擁有一個用戶控件,它將一組人(屬性「數據」)並顯示在列表框中。 當我運行我的應用程序沒有顯示在列表框中。你能指出我做錯了什麼嗎? 謝謝!WPF用戶控件

public class Person 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
    public override string ToString() 
    { 
     return Name + "(" + Age + ")"; 
    } 
} 

用戶控制: (uc1.xaml.cs)

public partial class uc1 
{ 
    public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof (List<Person>), typeof (uc1)); 

    public List<Person> Data 
    { 
     get { return (List<Person>) GetValue(DataProperty); } 
     set { SetValue(DataProperty, value); } 
    } 

    public uc1() 
    { 
     InitializeComponent(); 
    } 

    private void UserControl_Loaded(object sender, RoutedEventArgs e) 
    { 
     DataContext = Data; 
    } 
} 

(uc1.xaml)

<ListBox ItemsSource="{Binding Name}" /> 

回答

3

ItemsSource屬性控制着顯示在項目的列表列表框。如果您希望ListBox爲每個人顯示一行,則需要將ItemsSource設置爲直接綁定到DataContext。然後,您使用DisplayMemberPath屬性來控制要顯示的Person類的哪個屬性。

這是我的示例代碼,適合我。 人員類是相同的。

的Window1.xaml.cs:

public partial class Window1 : Window 
{ 
    public Window1() 
    { 
     InitializeComponent(); 
     List<Person> Data = new List<Person>(); 
     Data.Add(new Person { Name = "Test 1", Age = 5 }); 
     Data.Add(new Person { Name = "Test 2", Age = 10 }); 
     this.DataContext = Data; 
    } 
} 

的Window1.xaml

<ListBox ItemsSource="{Binding}" DisplayMemberPath="Name" />