【问题标题】:Passing multiple bindings into a ContentControl and Datatemplate将多个绑定传递到 ContentControl 和 Datatemplate
【发布时间】:2016-03-17 23:27:32
【问题描述】:

我正在开发一个媒体应用程序,我有一个设置窗口,其中有一个带有 3 个组合框的堆栈面板。这些组合框的 ItemSource 都绑定到同一个 List(Of SoundDevice) 以向用户显示所有可用的声音计算机上的设备。

这些组合框 SelectedValue 中的每一个都绑定到我的 SettingsClass 对象的子类(称为 SoundDevicesClass)上的不同公共属性,允许用户为不同的任务选择不同的设备。

我现在想在绑定到我的 SoundDevicesClass 的另一个实例的应用程序的另一个区域中重新使用这个相同的堆栈面板。

我的计划是将堆栈面板移动到 DataTemplate 中,然后将其放在我的设置窗口上的 ContentControl 中。然后可以通过

轻松将其绑定到后端对象
Content="{Binding Settings.SoundDevices}".

我的问题是我应该将组合框 ItemsSource 绑定到什么?在设置窗口中,它使用 {binding ElementName=SettingsWindow,Path=AllowedSoundDevices} 绑定到设置窗口的一个名为 AllowedSoundDevices 的属性,该属性工作正常,但如果我将数据模板移动到共享资源字典显然将无法工作。

我的第一个想法是定义一个名为 SoundDevicesSettingsClass 之类的新类,例如:

Public Class SoundDevicesSettingsClass
  Public Property AllowedSoundDevices as AllowedSoundDevicesClass
  Public Property SoundDevices as SoundDevicesClass
End Class

然后将 Content 绑定设置为该类的实例。

这是最好的方法还是我可以遵循更好的做法?

感谢所有帮助!

【问题讨论】:

    标签: wpf vb.net binding datatemplate contentcontrol


    【解决方案1】:

    如果 ItemsSource 引用等效数据而不管显示的是什么类型的视图,则创建额外的 ViewModel。将数据放入其中并将 StackPanel 的 DataContext 设置为该 ViewModel 对象。无论你把 StackPanel 放在哪里,它都是独立的,因为它的 DataContext 已经设置好了。

    【讨论】:

    • 你能给我一个例子,说明如何在 ResourceDictionary 中设置 DataContext 吗?您的意思是创建一个具有共享/静态属性集的 ViewModel,因此它可以在全球范围内使用吗?如果是这样,你知道绑定到静态类的语法是什么吗?
    猜你喜欢
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多