Wpf将自定义类与列表绑定到ListBox

时间:2015-08-18 05:40:48

标签: c# wpf xaml

我是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 as field的类,所以我的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.Lst绑定到ListBox。有人可以解释一下吗?

2 个答案:

答案 0 :(得分:3)

您必须对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>

答案 1 :(得分:2)

您必须使用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;
}