【问题标题】:SelectedItem dependency property never updates from UserControlSelectedItem 依赖属性永远不会从 UserControl 更新
【发布时间】:2014-04-03 20:15:19
【问题描述】:

我有一个包含ListBoxUserControl,我正在尝试启用与ListBox 的各个部分(ItemsSourceSelectedItemItemTemplate)的外部绑定。我的理解是依赖属性是实现这一目标的最佳方式:

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

ItemTemplateItemsSource DP 工作正常。但是,当我像这样将UserControl 添加到Window 时:

<local:CellComboBoxControl Grid.Column="1" 
    ItemsSource="{Binding VolDefs}" 
    SelectedItem="{Binding VolDef}">

SelectedItem 未按预期运行。在这里,我希望ListBoxSelectedItem 在用户单击列表框项时更新源属性VolDef。这似乎没有发生。

所以ItemTemplateItemSource 绑定的数据流是“源到控制”并且它们工作正常,但是SelectedItem 绑定需要是“控制到源”而不是.这是依赖属性的限制吗?有没有其他方法可以做到这一点?

【问题讨论】:

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


    【解决方案1】:

    尝试更新您的 Itemsource 依赖属性以包含以下内容:

    new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault))
    

    重要的是双向绑定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多