进行WPF界面设计的时候,我们希望设计的时候显示两个部件以方便设计,而在运行的时候,我可以控制两个控件的显示是互斥的,甚至可以同时显示或者同时消失。这里显示一个示例,显示如何实现互斥的显示。
图1. 设计时的效果
图2. 运行时的显示效果1
图3. 运行时的显示效果2
<Window x:Class="TempCodeTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TempCodeTest"
mc:Ignorable="d"
x:Name="_this"
DataContext="{Binding ElementName=_this}"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding PartAGridHeight}" />
<RowDefinition Height="{Binding PartBGridHeight}" />
</Grid.RowDefinitions>
<Button x:Name="SwitchButton" Margin="5" Content="Switch" Click="SwitchButton_Click"/>
<Button Content="Part A" Grid.Row="1" Background="Green"/>
<Button Content="Part B" Grid.Row="2" Background="Red"/>
</Grid>
</Window>
上面代码的关键部分:
<!--数据上下文的绑定-->
x:Name="_this"
DataContext="{Binding ElementName=_this}"
<!--绑定Row的高度-->
<RowDefinition Height="{Binding PartAGridHeight}" />
<RowDefinition Height="{Binding PartBGridHeight}" />
下面的代码实现了数据模型的部分
using System.ComponentModel;
using System.Windows;
namespace TempCodeTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#region Part A Part B Switch 部件A与部件B的相互切换
private bool _isShowingB = false;
public bool IsShowingB
{
get { return _isShowingB; }
set
{
_isShowingB = value;
OnPropertyChanged(nameof(IsShowingB));
OnPropertyChanged(nameof(PartAGridHeight));
OnPropertyChanged(nameof(PartBGridHeight));
}
}
public GridLength PartAGridHeight => IsShowingB ? new GridLength(0) : new GridLength(1, GridUnitType.Star);
public GridLength PartBGridHeight => IsShowingB ? new GridLength(1, GridUnitType.Star) : new GridLength(0);
#endregion
public MainWindow()
{
InitializeComponent();
}
private void SwitchButton_Click(object sender, RoutedEventArgs e)
{
IsShowingB = !IsShowingB;
}
}
}
关键部分:
- 实现了
INotifyPropertyChanged
接口; -
#region
与#endregion
之间的部分; -
SwitchButton
的Click事件里切换显示的实现。