wpf 如何在 XAML 中将 List 作为 ItemSource 绑定到 ListView?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3039628/
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-09-08 21:51:20  来源:igfitidea点击:

How can I bind a List as ItemSource to ListView in XAML?

wpfdata-bindingxamllistviewcollections

提问by Jonas

I'm learning WPF and would like to have a collection similar to a LinkedList, to where I can add and remove strings. And I want to have a ListViewthat listen to that collection with databinding. How can I do bind a simple list collection to a ListViewin XAML?

我正在学习 WPF 并希望有一个类似于 LinkedList 的集合,我可以在其中添加和删除字符串。我想要一个ListView通过数据绑定来收听该集合的。如何将一个简单的列表集合绑定到ListViewXAML 中的 a?

My idea (not working) is something like this:

我的想法(不工作)是这样的:

<Window x:Class="TestApp.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <LinkedList x:Key="myList"></LinkedList> //Wrong
    <Window.Resources>
    <Grid>
    <ListView Height="100" HorizontalAlignment="Left" Margin="88,134,0,0" 
      Name="listView1" VerticalAlignment="Top" Width="120" 
      ItemsSource="{Binding Source={StaticResource myList}}"/> //Wrong
    </Grid>
</Window>

All my code (updated version, not working):

我所有的代码(更新版本,不工作):

<Window x:Class="TestApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" 
          Name="textBox1" VerticalAlignment="Top" Width="120" />
        <Button Content="Button" Height="23" HorizontalAlignment="Right" 
          Margin="0,12,290,0" Name="button1" VerticalAlignment="Top" Width="75" 
          Click="button1_Click" />
        <ListView Height="100" HorizontalAlignment="Left" Margin="88,134,0,0" 
          Name="listView1" VerticalAlignment="Top" Width="120" 
          ItemsSource="{Binding myList}"/>
    </Grid>
</Window>

C#-code:

C#-代码:

namespace TestApp
{
    public partial class MainWindow : Window
    {
        ObservableCollection<string> myList = new ObservableCollection<string>();
        public MainWindow()
        {
            InitializeComponent();
            myList.Add("first string");
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            myList.Add(textBox1.Text);
            textBox1.Text = myList.Count+"st";
        }
    }
}

回答by ckozl

The approach selected as an answer works fine... but I don't specifically like having to specify the DataContextprogrammatically while setting everything else in XAML, I don't feel like it's "proper" (maybe this is just me). So for the next person, or anyone else who thinks like me and finds this off a search engine (like i did), here is the way to do it in XAML:

选择作为答案的方法工作正常......但我并不特别喜欢DataContext在 XAML 中设置其他所有内容时必须以编程方式指定,我不觉得它是“正确的”(也许这只是我)。因此,对于下一个人,或其他像我一样思考并从搜索引擎中找到它的人(就像我一样),这是在 XAML 中执行此操作的方法:

C#

C#

public sealed partial class MainPage : Page
{
    public ObservableCollection<string> Messages { get; set; }

    public MainPage()
    {
        this.Messages = new ObservableCollection<string>();
        this.InitializeComponent();
    }
}

XAML

XAML

<Window
    ....
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    ...>

    <ListView ItemsSource="{Binding Messages}" ... />

</Window>

To be honest I think {Binding RelativeSource={RelativeSource Self}}should be the default value any top level element's (Page, Window, etc...) DataConextbecause it is simply how a lot of people expect it to work, I know it's how I assume it would work. Honestly, I feel like {Binding RelativeSource={RelativeSource Self}}is a bit verbose and almost long for a shorter syntax.

老实说,我认为{Binding RelativeSource={RelativeSource Self}}应该是任何顶级元素 ( Page, Window, 等...)的默认值,DataConext因为这只是很多人期望它工作的方式,我知道这是我认为它会工作的方式。老实说,我觉得{Binding RelativeSource={RelativeSource Self}}对于较短的语法来说有点冗长而且几乎很长。

回答by Wallstreet Programmer

You can only databind to public properties and you need to set the DataContext.

您只能将数据绑定到公共属性,并且需要设置 DataContext。

public partial class MainWindow : Window
{
    public ObservableCollection<string> myList { get; private set; }

    public MainWindow()
    {
        InitializeComponent();

        myList = new ObservableCollection<string>();
        myList.Add("first string");
        DataContext = this;
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        myList.Add(textBox1.Text);
        textBox1.Text = myList.Count + "st";
    }
}