将文本(TextBox
)和图片(Image
)放入Grid
中,创建所需的布局。自动调整大小。
然后,将每个文本和图像的Visibility
property绑定到某个对象的属性上,该对象存储选项中选择的状态。(最好的解决方案是在您自己的新类中存储此信息,并将该类的实例分配给窗口的DataContext
property。)
对于每个绑定,创建一个
值转换器,根据当前选项返回
Visibility.Visible
或
Visibility.Collapsed
,以确定相应元素是否可见。请保留HTML标签。
编辑:这里有一些示例代码:
假设您的非常简单的设置对象如下所示:
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.");
}
}
作为文本2始终可见,除了只显示一个文本的状态- GuiMode.OneText - 转换器返回相应的Visibility值。另请注意,该转换器仅假定传入的value是GuiMode值。为了正确处理,您应该检查value和targetType。完成后,您可以将转换器作为静态资源导入到Xaml中:
<Window.Resources>
<Text2VisibilityConverter x:Key="text2vis"/>
</Window.Resources>
根据您导入的命名空间,您可能需要在那里
添加适当的命名空间前缀,以便正确使用
Text2VisibilityConverter
。
然后,可以使用
Text2VisibilityConverter
将
text2的
Visibility
属性绑定到
GuiSettings
类的
Mode
属性,假设存储设置的
GuiSettings
实例已分配给窗口的
DataContext
属性。
<TextBlock Text="Text 2" Visibility="{Binding Mode, Converter={StaticResource text2vis}}"/>
一旦这个工作完成,您可以为其他控件的可见性添加更多的值转换器类。
Window.SizeToContent
设置为WidthAndHeight
?:http://msdn.microsoft.com/en-us/library/system.windows.window.sizetocontent.aspx - BoluDynamicResources
中获取并根据所选内容编程性地更改其值。首先,你是否熟悉面板的“模板”选项?如果是的话,你可以在ResourceDictionary
中创建4种不同的Styles
,每种都具有不同的模板(每一种都与你的设计相适应),并进行编程性更改。 - SonhjaWindow
随内容一起调整大小吗? - Bolu