我有两个面板,同一时间只应该显示一个。我通过点击按钮在它们之间切换,每个面板上都有一个按钮。
在 xaml 中是否有一种很好的方法可以做到这一点,而不需要使用 codebehind 或 viewmodel?
我有两个面板,同一时间只应该显示一个。我通过点击按钮在它们之间切换,每个面板上都有一个按钮。
在 xaml 中是否有一种很好的方法可以做到这一点,而不需要使用 codebehind 或 viewmodel?
实际上,这是可能的,但相当棘手。
我的示例不需要任何代码后台,实际上也不需要任何值转换器。
以下是代码:(现在是简化版本,感谢@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
的想法来自于SO上的其他问题
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<TabControl BorderThickness="0" Padding="0">
<TabControl.Resources>
<Style TargetType="TabItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabItem">
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.Resources>
<TabItem Header="Not shown">
<Grid Background="Red"/>
</TabItem>
<TabItem>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">Tab 2
</TextBlock>
</TabItem>
</TabControl>
</Grid>
</P
IValueConverter
的小技巧应该能解决问题。虽然它不是纯粹的XAML,但它不在代码后台并且可以重复使用。public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (Visibility)value == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
}
我不这么认为。你需要使用viewmodel或codebehind。使用带有DataTrigger的样式,并将可见性属性的值绑定到viewmodel中的一个属性,避免使用codebehind。