我的UserControl
包含ListBox
,我试图启用对各个部分的外部绑定(ItemsSource
,SelectedItem
,{{1 } {} {}}。我的理解是依赖属性是实现这一目标的最佳方法:
ItemTemplate
ListBox
和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
DP工作正常。但是,当我将ItemTemplate
添加到ItemsSource
时,就像这样:
UserControl
Window
的行为不符合预期。在这里,我希望<local:CellComboBoxControl Grid.Column="1"
ItemsSource="{Binding VolDefs}"
SelectedItem="{Binding VolDef}">
的{{1}}在用户点击列表框项时更新源属性SelectedItem
。这似乎没有发生。
所以SelectedItem
和ListBox
绑定的数据流是&#34;源到控制&#34;并且他们工作正常,但VolDef
绑定需要&#34;控制到源&#34;它没有。这是依赖属性的限制吗?还有另一种方法可以实现这个目标吗?
答案 0 :(得分:0)
尝试更新Itemsource依赖属性以包含此内容:
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault))
重要的是双向约束。