小编典典

如何在WPF / WP7中将数据列表绑定到ListBox?

c#

我正在尝试将字符串值列表绑定到列表框,以便逐行列出它们的值。现在我用这个:

<ListBox Margin="20" ItemsSource="{Binding Path=PersonNames}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Path=Id}"></TextBlock>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

但是我不知道我应该在文本块中放入什么,而不是Id,因为它们都是字符串值,而不是自定义类。

另外,当我在MainPage中将其作为MainPage.PersonNames时,它抱怨没有找到PersonNames。

我将数据上下文设置为:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

我做错了吗?


阅读 320

收藏
2020-05-19

共1个答案

小编典典

如果简单地说,您的ItemsSource是这样绑定的:

YourListBox.ItemsSource = new List<String> { "One", "Two", "Three" };

您的XAML应该如下所示:

<ListBox Margin="20" Name="YourListBox">
    <ListBox.ItemTemplate> 
        <DataTemplate> 
            <StackPanel Orientation="Horizontal"> 
                <TextBlock Text="{Binding}" /> 
            </StackPanel> 
        </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox>

更新:

这是使用DataContext时的解决方案。以下代码是您将传递给页面的DataContext的ViewModel和DataContext的设置:

public class MyViewModel
{
    public List<String> Items
    {
        get { return new List<String> { "One", "Two", "Three" }; }
    }
}

//This can be done in the Loaded event of the page:
DataContext = new MyViewModel();

您的XAML现在看起来像这样:

<ListBox Margin="20" ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这种方法的优点是,您可以在MyViewModel类中放置更多的属性或复杂的对象,并将其提取到XAML中。例如,传递一个Person对象列表:

public class ViewModel
{
    public List<Person> Items
    {
        get
        {
            return new List<Person>
            {
                new Person { Name = "P1", Age = 1 },
                new Person { Name = "P2", Age = 2 }
            };
        }
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

和XAML:

<ListBox Margin="20" ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Path=Name}" />
                <TextBlock Text="{Binding Path=Age}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

希望这可以帮助!:)

2020-05-19