【问题标题】:WPF Databinding between two usercontrols两个用户控件之间的 WPF 数据绑定
【发布时间】:2013-06-03 19:35:41
【问题描述】:

我将尝试提供有关此问题的更多详细信息 在 WPF 应用程序中,在“主窗口”的左侧,我有一个包含列表框的 UserControl,如下所示

<UserControl.Resources>
    <ObjectDataProvider x:Key="viewModel" ObjectType="{x:Type vm:TemplateListViewModel}"/>
</UserControl.Resources>   
<StackPanel>
    <ListBox Height="Auto" Name="TemplateList"  ItemsSource="{Binding Source={StaticResource viewModel}, Path=TemplateNames}"     
</StackPanel>

如图所示,列表框项是通过 viewModel 从 xml 文件中获取的。 现在我有另一个包含标签的 usercontrol2 来回显“模板列表”中的选择。 同样在此标签下,我还有另一个包含数据网格的 usercontrol3,这些数据将基于标签从 xml 文件中获取,或者通过 usercontrol3 的视图模型从窗口左侧的列表框中进行选择。 所以问题是如何将“SelectedItem”或“SelectedIndex”传递给Label和datagrid的viewModel? 我知道当我将标签绑定到具有“elementName”和“SelectedItem”路径的列表框时它会起作用。现在我不知道如何处理用户控件和“ObjectDataProvider”。我按照下面的建议进行了尝试,但无法解决。到目前为止,对于 usercontrol2,如果我使用与上面相同的 ObjectDataProvider,我可以让这个标签作为

<Label Name="TemplateNameLabel" Content="{Binding Source={StaticResource viewModel}, Path=TemplateNames[0]}" />

如果是“XmlNodeList”类型的“TemplateNames”,因为它是从 xml 文件中读取的。但我真正想要的是类似的东西

<Label Name="TemplateNameLabel" Content="{Binding Source={StaticResource viewModel}, Path=TemplateNames[SelectedIndex]}" />

这可以在没有任何命令的情况下完成吗,就像在不涉及用户控制的情况下绑定到“元素名称”一样? 谢谢。

【问题讨论】:

  • 在 ViewModel 中放置一个SelectedItem 属性,并从第二个 ViewModel 引用该属性。组合 UI 的不同部分通常由 ViewModel 之间的通信解决,而不是 View。
  • @user2417994,你的问题还适用吗?

标签: wpf


【解决方案1】:

我删除了不重要的属性以突出显示主要内容:

 <ListBox Name="TemplateList" ItemsSource="{Binding Source={StaticResource viewModel}, Path=TemplateNames}" SelectedItem="{Binding Path=SelectedTemplate, Mode=OneWayToSource}" /> 

请注意,您将需要 SelectedTemplate 属性和 TemplateName 类型的公共设置器 - 与 TemplateNames 中的单个元素使用的类型相同> ViewModel 中的集合。在该设置器中,您可以将值传递给您需要的任何其他视图模型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2016-04-22
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    相关资源
    最近更新 更多