我有一个WPF应用程序,我们需要根据配置文件设置重新编写它。App.xaml的简单版本是:
App.xaml
<Application>
...
<Application.Resources>
<ResourceDictionary x:Key="NormalMain">
<ImageBrush x:Key="BackgroundBrush" ImageSource="Images/welcome.png"/>
</ResourceDictionary>
<ResourceDictionary x:Key="AlternateMain">
<SolidColorBrush x:Key="BackgroundBrush" Color="LightGreen"/>
</ResourceDictionary>
</Application.Resources>
...
</Application>我希望基于配置文件设置在运行时加载资源管理器。我已经连接了绑定并知道它可以工作,但是我无法确定合并这个特定字典的方法。
MainWindowView.xaml
<Window
(...)
d:DataContext="{d:DesignInstance designer:DesignMainWindowViewModel, IsDesignTimeCreatable=True}"
Background="{StaticResource BackgroundBrush}">
...
<Window.Resources>
//Load dictionary based on binding here?
</Window.Resources>
</Window>其中MainWindowViewModel很简单,如:
MainWindowViewModel.cs
public class MainWindowViewModel {
public bool IsAlternate {get;set;}
}有什么办法能做到这一点吗?
编辑:我不想在代码背后加载,而且在这种情况下,包语法看起来不像引擎构建的那样。
编辑2:我在App.xaml中使用这段代码有点接近:
<StaticResource ResourceKey="{Binding Path=IsAlternate, Converter={StaticResource BoolToResourceKeyId}}" />但在我看来,这会引起一堆奇怪的错误。
发布于 2014-07-01 17:35:48
经过几个小时的战斗,我找到了另一种处理情况的方法。
我为在app.xaml中工作的控件创建了两种样式:
App.xaml
...
<valueConverters:IsMainToStyleConverter x:Key="IsMainToStyleConverter" />
<Style x:Key="Main" TargetType="Window">
<Setter Property="Background" Value="{StaticResource MainBackgroundBrush}" />
</Style>
<Style x:Key="Alternate" TargetType="Window">
<Setter Property="Background" Value="{StaticResource AlternateBackgroundBrush}" />
</Style>
...然后定义一个转换器,用于定位样式:
IsMainToStyleConverter.cs
public class IsMainToStyleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return Application.Current.TryFindResource((value is bool && ((bool)value) ? "Main" : "Alternate"));
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}并修复了我的MainWindowView:
MainWindowView.xaml
<Window
...
d:DataContext="{d:DesignInstance designer:DesignMainWindowViewModel, IsDesignTimeCreatable=True}"
Style="{Binding IsMain, Converter={StaticResource IsMainConverter}}">
...
</Window>现在,只要我的视图模型具有正确的属性,转换器就会处理定位样式资源并切换到它,而不必担心超越模式关注点或诸如此类的问题。
发布于 2014-07-01 12:47:59
我认为在基于绑定的XAML中没有这样做的语法。
但是,您可以做的是在viewModel的PropertyChanged事件上创建一个事件处理程序,在这个处理程序中,检查"IsAlternate“的值,然后使用:
Application.Current.Resources.MergedDictionaries.Add并打包URI,以添加/删除正确的资源字典
https://stackoverflow.com/questions/24510064
复制相似问题