子控件在父控件内部不可见的可见性

时间:2018-12-18 01:13:30

标签: wpf xaml

我在StackPanel内的Grid内有一个UserControl。我已基于StackPanel中存在的名为ShowInstrumentAction的属性设置了ViewModel的可见性,该属性设置为DataContext。此操作工作正常。

但是我在此StackPanel中有一个按钮(请参阅PrimeFlush3TimesButton),我希望它可以根据其他条件显示出来。但是,子级别的可见性不起作用。

是否可以进行这种绑定?
还是应该在按钮上写可见性样式?
我不确定什么是正确的方法。请帮忙。

<StackPanel x:Name="InstrumentOperationsPanel" Visibility="{Binding DataContext.ShowInstrumentAction,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}},Converter={StaticResource boolToVisibility}}" Orientation="Horizontal" Grid.Row="0" HorizontalAlignment="Center">
    <Button x:Name="PrimeButton"
            Content="{StaticResource InstrumentPrime}"
            Margin="{StaticResource AllControlsMargin}" Command="{Binding DataContext.InstrumentPrimeCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}}}">
    </Button>
    <Button x:Name="FlushButton"
            Content="{StaticResource InstrumentFlush}"
            Margin="{StaticResource AllControlsMargin}" Command="{Binding DataContext.InstrumentFlushCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}}}">
    </Button>
    <Button x:Name="PrimeFlush3TimesButton"
            Content="{StaticResource PrimeAndFlush3Times}"
            Margin="{StaticResource AllControlsMargin}"
            Visibility="{Binding DataContext.IsBuiltInUser,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl},AncestorLevel=3},Converter={StaticResource boolToVisibility}}"
            Command="{Binding DataContext.InstrumentPrimeAndFlush3TimesCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}}}">
    </Button>
</StackPanel>

1 个答案:

答案 0 :(得分:0)

使用ElementBinding。命名用户控件。

    <Button x:Name="PrimeFlush3TimesButton"
        Content="{StaticResource PrimeAndFlush3Times}"
        Margin="{StaticResource AllControlsMargin}"
        Visibility="{Binding ElementName=UserControlName,Path=DataContext.IsBuiltInUser,Converter={StaticResource boolToVisibility}}"
        Command="{Binding ElementName=UserControlName,Path=DataContext.InstrumentPrimeAndFlush3TimesCommand}">
        </Button>