C# WPF 绑定集合到列表视图

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

C# WPF binding collection to the listview

c#wpfxamllistviewdata-binding

提问by Dmytro

I'm new to data binding in WPF and trying to understand concepts. What I'm trying to do is bind observable collection data to list view. For that purposes I have created two classes:

我不熟悉 WPF 中的数据绑定并试图理解概念。我想要做的是将可观察的集合数据绑定到列表视图。为此,我创建了两个类:

public class Employee_list
    {
        public ObservableCollection<Employee> list = new ObservableCollection <Employee>();
        public Employee_list()
        {
        }
    }

    public class Employee
    {
        public string name { get; set; }
        public string surname { get; set;}
        public Employee(string name, string surname)
        {
            this.name = name;
            this.surname = surname;
        }
    }

In the main window I've instantiated my list of Employees:

在主窗口中,我已经实例化了我的员工列表:

    public MainWindow()
    {
        InitializeComponent();
        Employee_list l = new Employee_list() { list = { new Employee("Alex", "Z"), new Employee ("Alex", "K")}};            
    }

Now I need to bind content of this list to ListView:

现在我需要将此列表的内容绑定到 ListView:

I understand that I can do it in three ways as per - 1

我知道我可以通过三种方式做到这一点 - 1

  1. RelativeSource: Relative source is one of the properties on a binding that can point to relative source markup extension that tells where the source can be found in hierarchy. In simple words, it is the relative path in the element hierarchy.

  2. ElementName: Another way of specifying a source is by using an ElementName in which another element is present in the current UI that can be used as a source object. Here the source object must be part of the visual tree.

  3. Source: Another way is by using the Source property on a binding. This source property must point to some object reference and the only better way to get an object reference down into the Source property is to use a static resource that points to some object in a resource collection.

  1. 相对来源:相对来源是绑定上的属性之一,可以指向相对来源标记扩展,该扩展表明可以在层次结构中找到来源。简单来说,它是元素层次结构中的相对路径。

  2. ElementName:另一种指定源的方法是使用 ElementName,其中当前 UI 中存在另一个可用作源对象的元素。这里源对象必须是可视化树的一部分。

  3. 来源:另一种方法是在绑定上使用 Source 属性。此源属性必须指向某个对象引用,而将对象引用向下传入 Source 属性的唯一更好方法是使用指向资源集合中某个对象的静态资源。

I'm try to do it via Source and Resources, but in that case I am able to specify class itself and not a specific collection with content:

我尝试通过 Source 和 Resources 来完成,但在这种情况下,我可以指定类本身而不是包含内容的特定集合:

<Window.Resources>
    <localc:Employee_list x:Key="EmployeeList" />
</Window.Resources>

Could you please help me to understand how I can do it and what is the proper way to do it?

您能否帮助我了解如何做到这一点以及正确的做法是什么?

XAML:

XAML:

<Window x:Name="mw" 
x:Class="binding_testing.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:localc="clr-namespace:binding_testing"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <localc:Employee_list x:Key="EmployeeList" />
</Window.Resources>
<Grid>
    <ListView Name="myListBox" HorizontalAlignment="Left" Height="89" Margin="75,77,0,0" VerticalAlignment="Top" Width="393"
         ItemsSource="{Binding Source={StaticResource EmployeeList}}" >
        <ListView.View>
            <GridView >
                <GridViewColumn Header="Surname" Width="Auto" DisplayMemberBinding="{Binding surname}" />
                <GridViewColumn Header="Name" Width="Auto" DisplayMemberBinding="{Binding name}" />
            </GridView>
        </ListView.View>
    </ListView>

</Grid>
</Window>

回答by Jens

So first name your Classesclear! Here you find the Microsoft Naming Guidelines.

所以首先命名你的Classes清晰!在这里您可以找到 Microsoft 命名指南。

I renamed your classes and properties to this:

我将您的类和属性重命名为:

public class EmployeeList
{
    public ObservableCollection<Employee> List { get; set; } = new ObservableCollection<Employee>();
}

public class Employee
{
    public string Name { get; set; }
    public string SurName { get; set; }
    public Employee(string name, string surName)
    {
        this.Name = name;
        this.SurName = surName;
    }
}

Make sure that all Propertiesare publicand also are properties. Because Listwas just a fieldin your code.

确保所有Properties都是public并且也是properties。因为List只是您代码中的一个字段

Then i recommend to introduce the class View. This is also a concept of the MVVM pattern, but i think it makes the code easier so this is good in two ways:

然后我建议介绍一下这门课View。这也是MVVM 模式的一个概念,但我认为它使代码更容易,所以这有两个好处:

public class View
{
    public EmployeeList EmployeeList { get; set; }

    public View()
    {
        EmployeeList = new EmployeeList() { List = { new Employee("Alex", "Z"), new Employee("Alex", "K") } };
    }
}

As you can see View holds an instance of the EmployeeList.

如您所见, View 包含EmployeeList.



Now you just need to set the DataContext of your window to the Viewand bind to the properties you want to:

现在,您只需要将窗口的 DataContext 设置为View并绑定到您想要的属性:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new View();
    }
}

The above code creates a new instance of the Viewclass and sets this as the new DataContext.

上面的代码创建了一个View类的新实例并将其设置为新的DataContext.

Now you just need to bind the ItemsSourceof the ListViewto EmployeeList.Listand set the DisplayMemeberBindings:

现在你只需要绑定ItemsSourceListViewEmployeeList.List,并设置DisplayMemeberBindingS:

<Grid>
    <ListView ItemsSource="{Binding EmployeeList.List}" >
        <ListView.View>
            <GridView >
                <GridViewColumn Header="Surname" DisplayMemberBinding="{Binding SurName}" />
                <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" />
            </GridView>
        </ListView.View>
    </ListView>
</Grid>


The Problems of your codewere that you had two instances of EmployeeList

你的代码的问题是你有两个实例EmployeeList

  1. Defined in the XAML
  2. Created in the Constructor of the Window
  1. 在 XAML 中定义
  2. 在窗口的构造函数中创建

Moreover you were not able to bind to the ObservableCollectionbecause it was not a Property. You only can bind to properties. A binding to fields is not possible. So make clear you have a get {...}or/and set {...}for the properties you want.

此外,您无法绑定到 ,ObservableCollection因为它不是Property. 您只能绑定到属性。无法绑定到字段。所以要明确你有一个get {...}或/和set {...}你想要的属性。

回答by AnjumSKhan

Do following changes :

做以下更改:

  1. Expose your collection as a property as DataBinding works with properties and not fields.

    public class Employee_list
    { 
        ObservableCollection<Employee> list = new ObservableCollection <Employee>();
    
        public ObservableCollection<Employee> List1
        {
            get { return list; }
        }
    
        public Employee_list()
        {
            List1.Add(new Employee("Alex", "Z"));
            List1.Add(new Employee("Alex", "K"));
        }
    }
    
  2. Instead of ItemsSource, bind DataContext, and then use your Collection property as ItemsSource like :

    <ListView ... 
         DataContext="{Binding Source={StaticResource EmployeeList}}" ItemsSource="{Binding List1}" >
    
  1. 将您的集合作为属性公开,因为 DataBinding 使用的是属性而不是字段。

    public class Employee_list
    { 
        ObservableCollection<Employee> list = new ObservableCollection <Employee>();
    
        public ObservableCollection<Employee> List1
        {
            get { return list; }
        }
    
        public Employee_list()
        {
            List1.Add(new Employee("Alex", "Z"));
            List1.Add(new Employee("Alex", "K"));
        }
    }
    
  2. 而不是 ItemsSource,绑定 DataContext,然后使用您的 Collection 属性作为 ItemsSource,如:

    <ListView ... 
         DataContext="{Binding Source={StaticResource EmployeeList}}" ItemsSource="{Binding List1}" >
    

Few good links :

几个好的链接:

  1. DataBinding - How to
  2. DataBinding - FAQ
  3. Scott's DataBinding tutorial
  1. 数据绑定 - 如何
  2. 数据绑定 - 常见问题
  3. Scott 的数据绑定教程