如何使用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
答案 0 :(得分:2)
您应该可以使用RelativeSource Binding
从UserControl
访问您的视图模型属性。我们的想法是使用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>