如何使用`Style`将子`UserControl`的依赖属性绑定到宿主元素的视图模型的属性?

时间:2014-12-16 13:33:24

标签: c# wpf xaml data-binding wpf-style

如何使用UserControl将子Style的依赖属性绑定到主机元素的视图模型的属性?

我尝试了下面的代码,MyBlock.BlockIsOnlyOne应该通过MyContainerViewModel.ViewModelIsOnlyOne {{1}绑定到视图模型的属性 - Style }}。但由于某种原因,它只是不起作用 - Setter的值永远不会改变,尽管MyBlock.BlockIsOnlyOne会发生变化......

容器XAML:

MyContainerViewModel.ViewModelIsOnlyOne

容器<UserControl x:Class="MyNs.MyContainer" ... > <UserControl.DataContext> <vc:MyContainerViewModel x:Name="TheDataContext"/> </UserControl.DataContext> <Grid> <Grid.Resources> <Style TargetType="{x:Type vc:MyBlock}"> <Setter Property="BlockIsOnlyOne" Value="{Binding ViewModelIsOnlyOne}"/> <!-- Tried this too, with no success: --> <!-- <Setter Property="BlockIsOnlyOne" Value="{Binding ViewModelIsOnlyOne, ElementName=TheDataContext}"/> --> </Style> </Grid.Resources> ... <vc:MyBlock DataContext="{Binding PortA[0]}" /> </Grid> </UserControl> (只有重要部分......):

ViewModel

[NotifyPropertyChangedAspect] // handles the INotifyPropertyChanged implementation... class MyContainerViewModel{ ... public bool ViewModelIsOnlyOne { get; private set; } ... } MyBlock

UserControl

1 个答案:

答案 0 :(得分:2)

您应该可以使用RelativeSource BindingUserControl访问您的视图模型属性。我们的想法是使用DataContext属性搜索视图模型设置为AncestorType的父视图 ...试试这个:

<Style TargetType="{x:Type vc:MyBlock}">
    <Setter Property="DataContext.BlockIsOnlyOne" Value="{Binding ViewModelIsOnlyOne, 
    RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
</Style>

如果这样取回了孩子UserControl.DataContext,那么您可以将RelativeSource.AncestorLevel Property设置为适当的级别,或者使用您的父级UserControl的名称/类型:

<Style TargetType="{x:Type vc:MyBlock}">
    <Setter Property="BlockIsOnlyOne" Value="{Binding DataContext.ViewModelIsOnlyOne, 
    RelativeSource={RelativeSource AncestorType={x:Type YourPrefix:MyContainer}}}" />
</Style>