两个用户控件之间的WPF数据绑定
我将试着给出这个问题的更多细节 在WPF应用程序中,在“mainwindow”的左侧有一个包含listBox的UserControl,如下所示两个用户控件之间的WPF数据绑定,wpf,Wpf,我将试着给出这个问题的更多细节 在WPF应用程序中,在“mainwindow”的左侧有一个包含listBox的UserControl,如下所示 <UserControl.Resources> <ObjectDataProvider x:Key="viewModel" ObjectType="{x:Type vm:TemplateListViewModel}"/> </UserControl.Resources> <StackPanel>
<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>
我删除了不重要的属性以突出主要内容:
<ListBox Name="TemplateList" ItemsSource="{Binding Source={StaticResource viewModel}, Path=TemplateNames}" SelectedItem="{Binding Path=SelectedTemplate, Mode=OneWayToSource}" />
请注意,您需要使用类型为TemplateName的公共setter的SelectedTemplate属性,该类型与ViewModel中的TemplateNames集合中的单个元素使用的类型相同。在该setter中,您可以将该值传递给所需的任何其他视图模型。在ViewModel中放置一个SelectedItem
属性,并从第二个ViewModel中引用该属性。组成UI的不同部分通常是通过视图模型之间的通信而不是视图之间的通信来解决的。@user2417994,您的问题是否仍然适用?
<Label Name="TemplateNameLabel" Content="{Binding Source={StaticResource viewModel}, Path=TemplateNames[SelectedIndex]}" />
<ListBox Name="TemplateList" ItemsSource="{Binding Source={StaticResource viewModel}, Path=TemplateNames}" SelectedItem="{Binding Path=SelectedTemplate, Mode=OneWayToSource}" />