C# 如何将字符串列表数据绑定到 WPF/WP7 中的 ListBox?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9391746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:10:40  来源:igfitidea点击:

How can I data bind a list of strings to a ListBox in WPF/WP7?

c#.netwpfwindows-phone-7data-binding

提问by Joan Venge

I am trying to bind a list of string values to a listbox so that their values are listed line by line. Right now I use this:

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

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

But I don't know what I am supposed to put into the textblock, instead of Id, since they are all string values, not custom classes.

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

Also it complains not having to find the PersonNames when I have it inside MainPage, as MainPage.PersonNames.

当我在 MainPage 中拥有 PersonNames 时,它也抱怨不必找到 PersonNames,如 MainPage.PersonNames。

I set the data context to:

我将数据上下文设置为:

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

I am doing it wrong?

我做错了吗?

采纳答案by Abbas

If simply put that your ItemsSource is bound like this:

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

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

Your XAML should look like:

您的 XAML 应如下所示:

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

Update:

更新:

This is a solution when using a DataContext. Following code is the viewmodel you will be passing to the DataContext of the page and the setting of the DataContext:

这是使用 DataContext 时的解决方案。以下代码是您将传递给页面的 DataContext 的视图模型和 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();

Your XAML now looks like this:

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

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

The advantage of this approach is that you can put a lot more properties or complex objects in the MyViewModel class and extract them in the XAML. For example to pass a List of Person objects:

这种方法的优点是您可以在 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; }
}

And the XAML:

和 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>

Hope this helps! :)

希望这可以帮助!:)

回答by HCL

If the items source is enumerable as string-entries, use the following:

如果项目源可作为字符串条目枚举,请使用以下内容:

<TextBlock Text="{Binding}"></TextBlock> 

You can use this syntax on any object. Generally, the ToString() -method will then called to get the value. This is in many cases very handy. But beware that no change notification will occur.

您可以在任何对象上使用此语法。通常,然后将调用 ToString() 方法来获取值。这在许多情况下非常方便。但请注意,不会发生更改通知。

回答by mindandmedia

You should show us the Code for PersonNames, and I am not sure, I understand your question, but maybe you want to bind it like this:

您应该向我们展示 PersonNames 的代码,我不确定,我理解您的问题,但也许您想像这样绑定它:

<TextBlock Text="{Binding Path=.}"/>

or

或者

<TextBlock Text="{Binding"} />

This will bind to the current element in the list. (Assuming PersonNames is a list of strings). Otherwise, you will see the class name in the list

这将绑定到列表中的当前元素。(假设 PersonNames 是一个字符串列表)。否则,您将在列表中看到类名

回答by Kevin K

You can do this without having to explicitly define the TextBlock control as a part of your ListBox (unless you want better formatting). The trick to getting the binding to trigger is using an ObservableCollection<string>instead of List<string>

您无需将 TextBlock 控件显式定义为 ListBox 的一部分即可执行此操作(除非您想要更好的格式)。使绑定触发的技巧是使用ObservableCollection<string>而不是List<string>

Window1.xaml

窗口1.xaml

<ListView Width="250" Height="50" ItemsSource="{Binding MyListViewBinding}"/>

Window1.xaml.cs

Window1.xaml.cs

public Window1()
{
   InitializeComponent();
   DataContext = this;

   // Need to initialize this, otherwise you get a null exception
   MyListViewBinding = new ObservableCollection<string>();
}

public ObservableCollection<string> MyListViewBinding { get; set; }

// Add an item to the list        
private void Button_Click_Add(object sender, RoutedEventArgs e)
{
   // Custom control for entering a single string
   SingleEntryDialog _Dlg = new SingleEntryDialog();

   // OutputBox is a string property of the custom control
   if ((bool)_Dlg.ShowDialog())
      MyListViewBinding.Add(_Dlg.OutputBox.Trim());
}