質問

Peopleのコレクション(プロパティ<!> quot; Data <!> quot;)を取得し、リストボックスに表示するユーザーコントロールが必要です。 アプリを実行すると、リストボックスに何も表示されません。私が間違っていることを指摘していただけますか? ありがとう!!!

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}" />
役に立ちましたか?

解決

ItemsSourceプロパティは、リストボックスに表示されるアイテムのリストを制御します。 ListBoxが各人に1行を表示するようにしたい場合、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" />
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top