且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF绑定列表,以多列列表框

更新时间:2022-06-03 03:20:15

下面是它适合在一起简而言之方式。

Here's the way it fits together in a nutshell.

首先,定义它保存你的数据结合的典范。

First, you define a model which holds your data for binding.

public sealed class MyListBoxItem
{
  public string Field1 {get;set;}
  public string Field2 {get;set;}
  public string Field3 {get;set;}
}

现在,你必须有持有这些模型绑定的类。这种类型的通常被称为视图模型;它presents信息到信息查看绑定基于从查看用户的输入。它的公共属性通常ObservableCollections和DependencyProperties这样在视图模型的变化将通过视图(UI)被自动拾取:

Now, you have to have a class that holds these models for binding. This type is often called the ViewModel; it presents information to the View for binding based on user input from the View. Its public properties are typically ObservableCollections and DependencyProperties so that changes in the ViewModel will be automatically picked up by the View (the UI):

public sealed class MyViewModel
{
  public ObservableCollection<MylistBoxItem> Items {get;private set;}
  public MyViewModel()
  {
    Items = new ObservableCollection<MyListBoxItem>();
    Items.Add(new MyListBoxItem{Field1="One", Field2="Two",Filed3="Three"};
  }
}

在codebehind为你的用户界面,在视图,您实例化你的视图模型,并将其设置在DataContext为您查看。

Within the codebehind for your UI, the "View", you instantiate your ViewModel and set it as the DataContext for your View.

public MyView()
{
  this.DataContext = new MyViewModel();
}

这是重要的,因为DataContext的流,通过可视化树。它是提供给在其上设置的每个子元素。

this is important as the DataContext "flows" through the visual tree. It is available to every child element on which it is set.

要显示的项目,我必须绑定ListView控件到DataContext的项目属性的ItemsSource(这被理解)。 ListView控件中的每一行都有它的DataContext设置为在项目属性中的每个单独的MyViewModel。所以,你必须在每个显示部件绑定到MyListBoxItem的属性。

To display the items, I must bind the ItemsSource of the ListView to the Items property of the DataContext (this is understood). Each row within the ListView has its DataContext set to each individual MyViewModel in the Items property. So you must bind each display member to the properties of the MyListBoxItem.

<ListView Name="RecordListView" ItemsSource="{Binding Items}">
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn Header="1" Width="Auto" DisplayMemberBinding="{Binding Path=Field1}" />
                <GridViewColumn Header="2" Width="50" DisplayMemberBinding="{Binding Path=Field2}" />
                <GridViewColumn Header="3" Width="100" DisplayMemberBinding="{Binding Path=Field3}" />
            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>

要更好地理解这整个过程,寻找高评级的问题在这里标记 [MVVM]

To understand this whole process better, search for high-rated questions here tagged [MVVM].

此外,为帮助调试您的绑定,对于详细的数据绑定配置调试:
WPF绑定列表,以多列列表框

ALSO, to help debug your bindings, configure debugging for verbose databinding: