SelectedItem依赖项属性永远不会从UserControl更新

时间:2014-04-03 20:15:19

标签: wpf vb.net visual-studio-2010 user-controls dependency-properties

我的UserControl包含ListBox,我试图启用对各个部分的外部绑定(ItemsSourceSelectedItem,{{1 } {} {}}。我的理解是依赖属性是实现这一目标的最佳方法:

ItemTemplate

ListBoxPublic 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。这似乎没有发生。

所以SelectedItemListBox绑定的数据流是&#34;源到控制&#34;并且他们工作正常,但VolDef绑定需要&#34;控制到源&#34;它没有。这是依赖属性的限制吗?还有另一种方法可以实现这个目标吗?

1 个答案:

答案 0 :(得分:0)

尝试更新Itemsource依赖属性以包含此内容:

new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault))

重要的是双向约束。