【发布时间】:2014-04-03 20:15:19
【问题描述】:
我有一个包含ListBox 的UserControl,我正在尝试启用与ListBox 的各个部分(ItemsSource、SelectedItem、ItemTemplate)的外部绑定。我的理解是依赖属性是实现这一目标的最佳方式:
Public Class CellComboBoxControl
Public Shared ReadOnly ItemsSourceProperty As DependencyProperty = _
DependencyProperty.Register("ItemsSource", GetType(IEnumerable), GetType(CellComboBoxControl),
New UIPropertyMetadata(Nothing))
Public Shared ReadOnly SelectedItemProperty As DependencyProperty = _
DependencyProperty.Register("SelectedItem", GetType(Object), GetType(CellComboBoxControl),
New UIPropertyMetadata(Nothing))
Public Shared ReadOnly ItemTemplateProperty As DependencyProperty = _
DependencyProperty.Register("ItemTemplate", GetType(DataTemplate), GetType(CellComboBoxControl),
New UIPropertyMetadata(Nothing))
Sub New()
InitializeComponent()
Me.cb_ListBox.SetBinding(ListBox.SelectedItemProperty, New Binding("SelectedItem") With {.Source = Me, .Mode = BindingMode.TwoWay})
Me.cb_ListBox.SetBinding(ListBox.ItemTemplateProperty, New Binding("ItemTemplate") With {.Source = Me, .Mode = BindingMode.TwoWay})
Me.cb_ListBox.DataContext = Me
End Sub
Public Property ItemsSource As IEnumerable
Get
Return CType(GetValue(ItemsSourceProperty), IEnumerable)
End Get
Set(value As IEnumerable)
SetValue(ItemsSourceProperty, value)
End Set
End Property
Public Property SelectedItem As Object
Get
Return CType(GetValue(SelectedItemProperty), Object)
End Get
Set(value As Object)
SetValue(SelectedItemProperty, value)
End Set
End Property
Public Property ItemTemplate As DataTemplate
Get
Return CType(GetValue(ItemTemplateProperty), DataTemplate)
End Get
Set(value As DataTemplate)
SetValue(ItemTemplateProperty, value)
End Set
End Property
ItemTemplate 和 ItemsSource DP 工作正常。但是,当我像这样将UserControl 添加到Window 时:
<local:CellComboBoxControl Grid.Column="1"
ItemsSource="{Binding VolDefs}"
SelectedItem="{Binding VolDef}">
SelectedItem 未按预期运行。在这里,我希望ListBox 的SelectedItem 在用户单击列表框项时更新源属性VolDef。这似乎没有发生。
所以ItemTemplate 和ItemSource 绑定的数据流是“源到控制”并且它们工作正常,但是SelectedItem 绑定需要是“控制到源”而不是.这是依赖属性的限制吗?有没有其他方法可以做到这一点?
【问题讨论】:
标签: wpf vb.net visual-studio-2010 user-controls dependency-properties