0

如何使用 将 childUserControl的 Dependency Property绑定Style到宿主元素的视图模型的属性?

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

容器 XAML:

<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: _

class MyBlock : UserControl{
    ...
    public static readonly DependencyProperty BlockIsOnlyOneProperty = DependencyProperty.Register(
        "BlockIsOnlyOne", typeof (bool), typeof (MyBlock), 
        new PropertyMetadata(default(bool), BlockIsOnlyOne_PropertyChangedCallback));

    private static void BlockIsOnlyOne_PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs a)
    {
        var @this = dependencyObject as MyBlock;
        if (@this == null) return;
        Trace.WriteLine(string.Format("Old: {0}, New: {1}", a.OldValue, a.NewValue)); // never seems to fire...
    }

    public bool BlockIsOnlyOne
    {
        get { return (bool) GetValue(BlockIsOnlyOneProperty); }
        set { SetValue(BlockIsOnlyOneProperty, value); }
    }
    ...
}
4

1 回答 1

2

您应该能够UserControl使用RelativeSource Binding. 这个想法是搜索视图模型设置为使用属性的父视图......试试这个:DataContextAncestorType

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

如果这UserControl.DataContext取而代之的是孩子,那么您可以将RelativeSource.AncestorLevel属性设置为适当的级别,或者改用您父母的名称/类型UserControl

<Style TargetType="{x:Type vc:MyBlock}">
    <Setter Property="BlockIsOnlyOne" Value="{Binding DataContext.ViewModelIsOnlyOne, 
    RelativeSource={RelativeSource AncestorType={x:Type YourPrefix:MyContainer}}}" />
</Style>
于 2014-12-16T14:12:41.560 回答