【问题标题】:Bind HashSet to a ListView Item (C#, WPF)将 HashSet 绑定到 ListView 项(C#、WPF)
【发布时间】:2009-06-15 15:25:19
【问题描述】:

我正在尝试将 HashSet 绑定到 ListView 项。我在这里记录了我的代码:

public class Person {
    public string Name { get; set; }
    public AddressList = new AddressList ();
}
public class AddressList : HashSet<Addresses>
{
    //
}
public class Addresses {
    public string Streetname { get; set; }
    public string City { get; set; }
}
public class PersonViewModel : INotifyPropertyChanged {
    private Person _person;

    public PersonViewModel(Person person)
    {
        _person= person; 
    }

    public string Name
    {
        get { return _person.Name; }
        set
        {
            _person.Name = value;
            OnPropertyChanged("Name");
        }
    }
    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}

 // This is how I add the DataContext: mainGrid.DataContext = _person //this is a PersonViewModel();
 // This is how I bind the DataObjects to the GUI Elements: <TextBox Name="TxtBoxName" Text="{Binding Path=.Name, Mode=TwoWay}"/>
 // How can I add in the same way a HashSet to a ListView Element in the WPF Gui? I tried something like {Binding Path=.Name, Mode=TwoWay}

谁能帮助我提示如何实现这一点?非常感谢!

干杯

【问题讨论】:

  • 此外,除非您为 Addresses 类添加(或需要)IEqualityComparer,否则我会避免使用 HashSet 而不是更简单的集合,例如 List
  • 但是HashSet不是更快吗?我实际上不需要任何特定的 HashSet 函数(“nice-to-have”唯一条目部分除外)..

标签: c# wpf inotifypropertychanged hashset


【解决方案1】:

要将集合绑定到ListView(或任何ItemsControl,就此而言),您需要设置其ItemsSource 属性。这应该绑定到您的 AddressList 类的实例,假设您希望在列表中显示该集合。

完成此操作后,您需要为ListView 中的每一列设置绑定,类似于示例代码底部的注释描述它的方式。

【讨论】:

    【解决方案2】:

    This example 绑定到 XML 数据源,但您应该能够根据需要对其进行调整。

    另请参阅 ListView here 的 MSDN 文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多