【问题标题】:vb.net WPF Binding a ListBox to an ObservableCollection(Of MyClass)vb.net WPF 将 ListBox 绑定到 ObservableCollection(Of MyClass)
【发布时间】:2015-08-04 04:44:05
【问题描述】:

所以,我可以创建一个 ObservableCollection(Of MyClass) 并声明它是一个公共属性。单击按钮后将创建此集合。如何将列表框控件绑定到它?这些是我的代码:

    Public Property StaticFailingPinListItem As New ObservableCollection(Of PinNameAndImageLocation)

    <ListBox Name="StaticFailingPinListBox" Grid.Row="1" Grid.Column="0" MinHeight="150" MinWidth="220" 
                                    FontSize="12" Margin="3" ItemsSource="{Binding}" />

PinNameAndImageLocation 有 2 个属性:PinName 和 ImageLocation。 我想在我的列表框中将 PinName 属性显示为项目.. 任何帮助将不胜感激。

【问题讨论】:

  • 你试过StaticFailingPinListBox.ItemsSource=yourObservableCollection
  • 你试过ItemSource="{Binding StaticFailingPinListItem}" DisplayMemberPath="PinName"
  • ^ 别忘了实现INotifyPropertyChanged

标签: wpf vb.net listbox


【解决方案1】:

1) 在YourClass 类中声明StaticFailingPinListItem 集合属性,并在该类中实现INotifyPropertyChanged Interface

2) 将Window.DataContext 设置为该类的一个实例:

DataContext = new YourClass

3) 在 XAML 中绑定到该属性:

<ListBox ItemsSource="{Binding StaticFailingPinListItem}" ... />

4) 覆盖PinNameAndImageLocation 类中的ToString 方法以返回PinName 属性值:

Public Overrides Function ToString() As String
    Return PinName 
End Function

这就是你需要做的。

【讨论】:

  • 你能进一步解释你的第一点吗?这是否意味着我必须在我自己创建的类而不是我的主用户控件中声明一个集合属性?
  • 虽然可能没有必要只为单个属性执行此操作,但通常创建一个类来表示您的窗口或UserControl 的所有数据。然后使用 INotifyPropertyChanged 接口通知 UI 此类中的属性更改。
猜你喜欢
  • 2013-12-31
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 1970-01-01
  • 2014-09-28
  • 2012-12-16
  • 1970-01-01
  • 2018-09-11
相关资源
最近更新 更多