问题描述
我所有的样式和模板都位于名为design.xaml"的资源字典中,因此在我拥有的每个用户控件中:
All my styles and templates are located in a resource dictionnary named "design.xaml" so in every Usercontrol I have :
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MyProject;component/design.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
但我想让用户通过创建 2 个资源字典来选择他喜欢的设计,其中包含相同的模板(每个模板具有相同的键,不同颜色).
But I'd like to let the user choose his preferred design by creating 2 resources dictionnaries with the same templates inside (same key for each template with different colors).
例如文件 design.xaml 和 design2.xaml
For example a file design.xaml and design2.xaml
我该怎么做?是否可以使用代码动态更改资源字典?
How can I do that ? Is it possible to change dynamically the resource dictionnary using code ?
谢谢!
推荐答案
ResourceDictionary1
<Style x:Key="StyleTitleText" TargetType="TextBlock">
<Setter Property="FontFamily" Value="Arial" />
<Setter Property="FontSize" Value="14"/>
<Setter Property="Foreground" Value="Green" />
</Style>
ResourceDictionary2
<Style x:Key="StyleTitleText" TargetType="TextBlock">
<Setter Property="FontFamily" Value="Arial" />
<Setter Property="FontSize" Value="14"/>
<Setter Property="Foreground" Value="Red" />
</Style>
MainWindow xaml
如果主题需要动态更新 UI(即无需重新加载整个 UI),您需要使用 DynamicResource 而不是 StaticResource.
You need to use DynamicResource over StaticResource if the themes need to update the UI dynamically (i.e. withoput entire UI reloading).
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="design.xaml" />
<ResourceDictionary Source="design2.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<StackPanel Orientation="Horizontal">
<ToggleButton Name="Radiobtn" Content="Switch ResourceDictionary" Height="35" FontSize="12" Margin="0,0,50,0" Click="RadioButton_Checked_1"></ToggleButton>
<TextBlock Style="{DynamicResource StyleTitleText}" Text="hfghfhgfhgfhgfghfhfhgf" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
</StackPanel>
c#
ResourceDictionary r1;
ResourceDictionary r0;
public MainWindow()
{
InitializeComponent();
r1 = this.Resources.MergedDictionaries[1];
r0 = this.Resources.MergedDictionaries[0];
this.Resources.MergedDictionaries.Remove(r1);
}
private void RadioButton_Checked_1(object sender, RoutedEventArgs e)
{
this.Resources.Clear();
if (Radiobtn.IsChecked == true)
{
this.Resources.MergedDictionaries.Add(r0);
}
else
{
this.Resources.MergedDictionaries.Add(r1);
}
}
这篇关于让用户更改资源字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!