Wpf将带有列表的自定义类绑定到ListBox

本文关键字:绑定 ListBox 自定义 列表 Wpf | 更新日期: 2023-09-27 18:08:20

我是WPF的新手,正在尝试绑定。现在我将自定义对象列表绑定到ListBox,如下所示:

public class Foo
{
    public string Name { get; set; }
}
这是我的c#代码:
public List<Foo> lst = new List<Foo>();
public MainWindow()
{
    Bar bar = new Bar();
    lst.Add(new Foo { Name = "111" });
    lst.Add(new Foo { Name = "222" });
    lst.Add(new Foo { Name = "333" });
    lst.Add(new Foo { Name = "444" });
    lst.Add(new Foo { Name = "555" });     
    this.DataContext = lst;
    InitializeComponent();
}

还有XAML:

<ListBox Height="139" HorizontalAlignment="Left" Margin="44,102,0,0" Name="listBox1" VerticalAlignment="Top" Width="350" 
             ItemsSource="{Binding}">
     <ListBox.ItemTemplate>
         <DataTemplate>
             <TextBlock Text="{Binding Name}"></TextBlock>
         </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>

这很好,但我想绑定一个类,其中包含List作为字段,所以我的c#代码看起来像:

public class Foo
{
    public string Name { get; set; }
}
public class Bar
{
    private List<Foo> lst;
    public List<Foo> Lst
    {
        get;
        set;
    }
    public Bar()
    {
        lst = new List<Foo>();
        lst.Add(new Foo { Name = "111" });
        lst.Add(new Foo { Name = "222" });
        lst.Add(new Foo { Name = "333" });
        lst.Add(new Foo { Name = "444" });
        lst.Add(new Foo { Name = "555" });            
    }
}

Bar bar=new Bar();
this.DataContext=bar;

当我这样做时,什么都不起作用。所以我不知道怎么把bar.LstListBox结合。有人能解释一下吗?

Wpf将带有列表的自定义类绑定到ListBox

您必须对您的Bar类做一些修改。

public class Bar
{
    private List<Foo> lst;
    public List<Foo> Lst
    {
        get { return lst;}        
    }
    public Bar()
    {
        lst = new List<Foo>();
        lst.Add(new Foo { Name = "111" });
        lst.Add(new Foo { Name = "222" });
        lst.Add(new Foo { Name = "333" });
        lst.Add(new Foo { Name = "444" });
        lst.Add(new Foo { Name = "555" });            
    }
}

在你的Xaml。

<ListBox Height="139" HorizontalAlignment="Left" Margin="44,102,0,0" Name="listBox1" VerticalAlignment="Top" Width="350" 
         ItemsSource="{Binding Lst}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"></TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

必须使用Lst属性而不是lst字段。最好使用AutoProperty,然后你的DataContext像这样:this.DataContext = bar.Lst;所以改变你的代码如下:

public class Bar
{
    public List<Foo> Lst { get; set; }
    public Bar()
    {
        Lst = new List<Foo>();
        Lst.Add(new Foo { Name = "111" });
        Lst.Add(new Foo { Name = "222" });
        Lst.Add(new Foo { Name = "333" });
        Lst.Add(new Foo { Name = "444" });
        Lst.Add(new Foo { Name = "555" });
    }
}

:

public MainWindow()
{
     InitializeComponent();
     Bar bar = new Bar();
     this.DataContext = bar.Lst;
}