UserControl可以通过自己的XAML隐藏自己

时间:2014-07-18 14:06:01

标签: c# .net wpf xaml user-controls

如果我有一个用户控件,我想作为叠加层,我想隐藏自己,可以这么说,当它不需要时。它将通过它具有父对象可以绑定的依赖属性来了解这一点。我的第一个想法是通过UC的大多数网格来做到这一点。所以像这样:

<UserControl x:Class="MyUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:valueConverters="clr-namespace:Some.Namespace;assembly=Some.Assembly">

    <UserControl.Resources>
        <valueConverters:VisibilityConverter x:Key="VisibilityConverter"/>
    </UserControl.Resources>

    <Grid DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl, Mode=FindAncestor}}"
          Visibility="{Binding ShowMyself, Converter={StaticResource VisibilityConverter}}">>
        .................
        .................
    </Grid>
</UserControl>

这很好用。现在,如果我想通过Parent对象隐藏控件,这很容易就像这样:

<controls:MyUserControl ShowMyself="{Binding ShowUserControl">
    .........
    .........
</controls:MyUserControl>

但是我想知道是否有可能做这样的事情所以控制本质上隐藏了自己:

<UserControl x:Class="MyUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:valueConverters="clr-namespace:Some.Namespace;assembly=Some.Assembly">

    <UserControl.Resources>
        <valueConverters:VisibilityConverter x:Key="VisibilityConverter"/>
    </UserControl.Resources>

    <UserControl.Visibility>
        <Binding Path="ShowMyself" Converter="{StaticResource VisibilityConverter}"/>
    </UserControl.Visibility>

    <Grid>
        .................
        .................
    </Grid>
</UserControl>

我意识到实际上可能没什么区别,这可能纯粹是学术性的,但看起来更“合适”。如果我尝试第二个场景,问题就变成了Binding在DataContext之外,并且看不到属性 - DataContext现在是父对象的那个,因为UserControl标签本身基本上不包含“肉”。

这是不可能的吗?

2 个答案:

答案 0 :(得分:3)

如果要在UserControl级别绑定Usercontrol的属性,请使用RelativeSource.Self作为绑定源

<UserControl ...>
    <UserControl.Resources>
        <valueConverters:VisibilityConverter x:Key="VisibilityConverter"/>
    </UserControl.Resources>
    <UserControl.Visibility>
        <Binding 
            RelativeSource="{RelativeSource Self}" 
            Path="ShowMyself" 
            Converter="{StaticResource VisibilityConverter}"/>
    </UserControl.Visibility>
    <!-- .... -->
</UserControl>

需要按此顺序以避免访问本地VisibilityConverter资源的问题

答案 1 :(得分:1)

您只需要一个RelativeSource Binding

<UserControl x:Class="MyUserControl"
...
    Visibility="{Binding ShowMyself, RelativeSource={RelativeSource 
    AncestorType={x:Type YourPrefix:MyUserControl}}, Converter="{StaticResource 
    VisibilityConverter}">
    ...
</UserControl>