c# - WPF 切换面板可见性

标签 c# wpf xaml panel visibility

我有两个面板,只有一个应该同时可见。我通过单击一个按钮在它们之间切换,每个面板上都有一个。

有没有在没有代码隐藏或 View 模型的情况下在 xaml 中执行此操作的好方法?

最佳答案

这实际上是可能的,但是非常棘手。

我的示例在没有任何代码隐藏的情况下运行,实际上也没有任何值转换器。

这是代码:(现在是简化版,感谢@H.B. 的想法)

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:sys="clr-namespace:System;assembly=mscorlib"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Page.Resources>
    <Style x:Key="RBToggleButtonStyle" TargetType="RadioButton">
      <Setter Property="Template">
         <Setter.Value>
           <ControlTemplate>
              <ToggleButton
                 IsChecked="{Binding IsChecked, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
                 Content="{Binding Content, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" />
           </ControlTemplate>
         </Setter.Value>
       </Setter>
       <Setter Property="Width" Value="150"/>
       <Setter Property="Height" Value="25"/>
       <Setter Property="HorizontalAlignment" Value="Right"/>
       <Setter Property="VerticalAlignment" Value="Bottom"/>
       <Setter Property="Margin" Value="15"/>
       <Setter Property="Content" Value="Hide"/>
    </Style>
    <Style x:Key="MyBorderStyle" TargetType="Border">
      <Style.Triggers>
        <DataTrigger Binding="{Binding IsChecked}" Value="True">
          <Setter Property="Visibility" Value="Hidden"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Page.Resources>
  <Grid>
    <Grid.ColumnDefinitions>
      <ColumnDefinition/>
      <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Border Background="Green" Grid.Column="0" Style="{StaticResource MyBorderStyle}" DataContext="{Binding ElementName=greenB}">
      <RadioButton x:Name="greenB" GroupName="x" Style="{StaticResource RBToggleButtonStyle}"/>
    </Border>
    <Border Background="Red" Grid.Column="1" Style="{StaticResource MyBorderStyle}" DataContext="{Binding ElementName=redB}">
      <RadioButton x:Name="redB" GroupName="x" Style="{StaticResource RBToggleButtonStyle}"/>
    </Border>
  </Grid>
</Page>

使用 ToggleButtons 的想法是从 some other question at SO 中窃取的

关于c# - WPF 切换面板可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6278720/

相关文章:

c# - WPF从按钮传递按钮内容?

c# - Wpf 中菜单项的选择性样式

c# - 如何更改基于 ViewModel 属性的自定义类型的 DataTemplate?

c# - 如何在 WPF DataTemplate 上使用 DataType 属性?

c# - UserControl 中的 ContentPresenter

c# - 在 FlipView 控件中捏合缩放和平移? Windows Phone 8.1 XAML Winrt 应用程序

c# - .Net Core开放外部终端

c# - Winforms ListView - 双击时停止自动检查

c# - 忽略异常类型 : multiple catch block vs. 类型查询的更好方法

c# - 如何模拟具有参数的异步保护方法?