1

VisibilityofContentPresenter设置为Collapsed并在运行时更改它Visibility时,会破坏保留在其内容中的元素的绑定。

XAML

<Grid>
    <Button x:Name="button"
            Width="100"
            Height="20"
            Margin="173,23,230,268"
            Click="button_Click"
            Content="Button" />

    <ContentPresenter x:Name="contentPresenter"
                      Margin="0,62,12,0"
                      Visibility="Collapsed">
        <ContentPresenter.Content>
            <StackPanel>
                <TextBox x:Name="test2"
                         Width="200"
                         Height="20" />
                <TextBox Width="200"
                         Height="20"
                         Text="{Binding ElementName=test2,
                                        Path=Text,
                                        Mode=TwoWay,
                                        UpdateSourceTrigger=PropertyChanged}" />
            </StackPanel>
        </ContentPresenter.Content>
    </ContentPresenter>
</Grid>

Code

private void button_Click(object sender, RoutedEventArgs e)
{
    if (contentPresenter.IsVisible == false)
    {
            contentPresenter.Visibility = System.Windows.Visibility.Visible;
    }
    else if (contentPresenter.IsVisible == true)
         {
             contentPresenter.Visibility = System.Windows.Visibility.Collapsed;
         }
}

任何一个帮助。

4

1 回答 1

0

如果您将内容放入用户控件中,您的绑定将起作用。如果您在运行时检查输出,您会看到存在绑定错误。表示没有带有“test2”的元素

<Grid>
    <Button x:Name="button"
        Width="100"
        Height="20"
        Margin="173,23,230,268"
        Click="button_Click"
        Content="Button" />
    <ContentPresenter x:Name="contentPresenter"
                  Margin="0,62,12,0"
                  Visibility="Collapsed">
        <ContentPresenter.Content>
            <WpfApplication1:UserControl1/>
        </ContentPresenter.Content>
    </ContentPresenter>
</Grid>

用户控制

<UserControl x:Class="WpfApplication1.UserControl1"
         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:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <StackPanel>
        <TextBox x:Name="test2"
                     Width="200"
                     Height="20" />
        <TextBox Width="200"
                     Height="20"
                     Text="{Binding ElementName=test2,
                                    Path=Text,
                                    Mode=TwoWay,
                                    UpdateSourceTrigger=PropertyChanged}" />
    </StackPanel>
</Grid>
</UserControl>
于 2013-05-27T07:07:50.433 回答