MyContent的可见性打破了ContentPresenter

时间:2018-03-12 21:05:21

标签: c# wpf

“MyContent的可见性打破了ContentPresenter”

在以下代码中,ContentPresenter应根据触发器呈现MyContent。当初始可见性更改为Hidden或ContentPresenter替换为ContentControl时,它似乎有效。

在ContentPresenter上使用可见性折叠有什么问题?

我有UserControl1有2个依赖属性:

public bool ShowMyContent
{
    get { return (bool)GetValue(ShowMyContentProperty); }
    set { SetValue(ShowMyContentProperty, value); }
}

public static readonly DependencyProperty ShowMyContentProperty = DependencyProperty.Register("ShowMyContent", typeof(bool), typeof(UserControl1));

public object MyContent
{
    get { return (object)GetValue(MyContentProperty); }
    set { SetValue(MyContentProperty, value); }
}

public static readonly DependencyProperty MyContentProperty = DependencyProperty.Register("MyContent", typeof(object), typeof(UserControl1));

和我的MainWindow依赖属性

public string MyProperty
{
    get { return (string)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}

public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(string), typeof(MainWindow), new FrameworkPropertyMetadata("MyDefaultValue"));

然后将以下XAML作为我的MainWindow:

<Window.Resources>
    <Style TargetType="{x:Type local:UserControl1}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:UserControl1}">
                    <!--  Try Visiblity="Hidden" or replace the ContentPresnter with ContentControl  -->
                    <ContentPresenter x:Name="Presenter"
                                      Content="{TemplateBinding MyContent}"
                                      Visibility="Collapsed" />
                    <ControlTemplate.Triggers>
                        <Trigger Property="ShowMyContent" Value="True">
                            <Setter TargetName="Presenter" Property="Visibility" Value="Visible" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<StackPanel>
    <local:UserControl1 x:Name="userControl1">
        <local:UserControl1.MyContent>
            <TextBox Text="{Binding Path=MyProperty, RelativeSource={RelativeSource AncestorType=local:MainWindow}}" />
        </local:UserControl1.MyContent>
    </local:UserControl1>
    <CheckBox IsChecked="{Binding Path=ShowMyContent, ElementName=userControl1}" />
</StackPanel>

0 个答案:

没有答案