将文本 (TextBox) 和图像 (Image) 放在 Grid 中以创建所需的布局。调整大小将自动进行。
然后,将每个文本和图像的Visibility property 绑定到某个对象的属性,该属性存储在选项中选择了哪个状态。 (最好的解决方案是将此信息存储在您自己的某个新类中,并将该类的一个实例分配给您窗口的DataContext property。
对于每个绑定,创建一个 value converter,它会根据相应元素在当前选项下是否可见或不可见而返回 Visibility.Visible 或 Visibility.Collapsed。
编辑:这是一些示例代码:
假设您非常简单的设置对象如下所示:
public enum GuiMode {
FourTexts,
ThreeTexts,
OneText,
ThreeTextsAndImage
}
public class GuiSettings : INotifyPropertyChanged
{
public PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private GuiMode mode = GuiMode.FourTexts;
public GuiMode Mode {
get {
return mode;
}
set {
if (mode != value) {
switch (value) {
case GuiMode.FourTexts:
case GuiMode.ThreeTexts:
case GuiMode.OneText:
case GuiMode.ThreeTextsAndImage:
mode = value;
OnPropertyChanged("Mode");
break;
default:
throw new InvalidEnumArgumentException("value", (int)value, typeof(GuiMode));
}
}
}
}
}
这存储了您的 GUI 的模式。注意INotifyPropertyChanged 的实现,因此当绑定到Mode 属性时,Mode 属性的更改将自动更新绑定到它的任何内容。
然后,例如,对于 text2,您可以编写以下值转换器:
public class Text2VisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
switch ((GuiMode)value) {
case GuiMode.OneText:
return Visibility.Collapsed;
default:
return Visibility.Visible;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException("This converter does not convert back.");
}
}
由于 text2 始终可见,除了只显示一个文本的状态 - GuiMode.OneText -,转换器返回相应的 Visibility 值。另请注意,此转换器仅假定传入的value 是GuiMode 值。要正确执行此操作,您应该检查value 和targetType 中的内容。
完成后,您可以将转换器作为静态资源导入您的 Xaml:
<Window.Resources>
<Text2VisibilityConverter x:Key="text2vis"/>
</Window.Resources>
根据您导入的命名空间,您可能需要在Text2VisibilityConverter 前面加上add the appropriate namespace prefix。
您的 text2 的 Visibility property 然后可以使用 Text2VisibilityConverter 绑定到 GuiSettings 类中的 Mode 属性,假设您存储的 GuiSettings 实例您的设置已分配给窗口的DataContext property:
<TextBlock Text="Text 2" Visibility="{Binding Mode, Converter={StaticResource text2vis}}"/>
一旦成功,您就可以为其他控件的可见性添加更多值转换器类。