【问题标题】:WPF binding Data into ListBox multiple columnsWPF 将数据绑定到 ListBox 多列
【发布时间】:2012-06-20 13:51:09
【问题描述】:

//嗨!我需要将我的数据放入包含多个列的列表框中我看到了这个链接stackoverflow.com...,但它谈到了每件事,但没有提到我可以将项目添加到列中的方式,请你解释一下如何将数据项添加到列中,谢谢很多。我成功地做了以下事情

<ListView.View>
     <GridView>
         <GridView.Columns>
              <GridViewColumn Header="1" Width="100" DisplayMemberBinding="{Binding Path=Field1}" />
              <GridViewColumn Header="2" Width="100" DisplayMemberBinding="{Binding Path=Field2}" />
              <GridViewColumn Header="3" Width="100" DisplayMemberBinding="{Binding Path=Field3}" />
         </GridView.Columns>
     </GridView>
</ListView.View>`

 public sealed class MyListBoxItem
    {
        public string Field1 { get; set; }
        public string Field2 { get; set; }
        public string Field3 { get; set; }
    }
    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", Field3 = "Three" });
        }
    }

【问题讨论】:

  • 感谢您的编辑我试图让它像这样但我做不到;)

标签: wpf data-binding mvvm listbox


【解决方案1】:

您需要在 Window1.xaml.cs 类的构造函数中设置包含ListBox 控件的Window(例如Window1)的DataContext 属性,如下所示:

public Window1()
{
    MyViewModel vm = new MyViewModel();

    this.DataContext = vm;
}

下一步是将 ListBox 控件(在 XAML 内)的 ItemsSource 属性设置为您在 ViewModel 类中提供的 Items 属性:

<ListBox ItemsSource="{Binding Path=Items}">
    <!--Other XAML-->
</ListBox>

此外,您还应该为您的MyListBoxItem 类实现INotifyPropertyChanged 接口,这在here in MSDN 中进行了解释。这是因为在您的 WPF 应用程序中实现 MVVM 模式。要求您实施更改通知以使 onewaytwoway 数据绑定工作(请参阅此以了解有关 DataBinding 的更多信息)。

这里是MVVM on MSDN的更详细的解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多