WPF:在运行时从App.xaml更改资源(颜色) [英] WPF: Changing Resources (colors) from the App.xaml during runtime
问题描述
我试图通过允许用户从颜色选择器"对话框中选择颜色,然后实时更改应用程序的样式(使用DynamicResource
)来使我的应用程序更具可定制性
I am trying to make my application more customizable by allowing users to pick a color from a Color Picker dialog, and then changing the style of the application in real time (with DynamicResource
)
如何更改app.xaml
中驻留的特定资源?
How do I go about in changing specific resources that reside in the app.xaml
?
我尝试过类似的方法,但是没有运气(只是测试):
I have tried something like this but no luck (just a test):
var colorDialog = new CustomControls.ColorPickerDialog();
var dResult = colorDialog.ShowDialog();
var x = Application.Current.Resources.Values.OfType<LinearGradientBrush>().First();
x = new LinearGradientBrush();
x.GradientStops.Add(new GradientStop(colorDialog.SelectedColor,1));
这是app.xaml
文件的摘录:
<Application.Resources>
<LinearGradientBrush x:Key="HeaderBackground" StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#82cb02" Offset="1"/>
<GradientStop Color="#82cb01" Offset="0.2"/>
<GradientStop Color="#629a01" Offset="0.5"/>
</LinearGradientBrush>
</Application.Resources>
为应用程序提供这种形式的可定制性(基本上只是更改一些颜色)的最佳方法是什么?
[更新]
我刚刚从先前提出并尝试过的问题中找到此答案它,但是我在给定答案的注释中提到了相同的 InvalidOperationException 异常Petoj.这是答案中的示例代码:
I just found this answer from a previous question that was asked, and tried it but I am getting the same InvalidOperationException exception Petoj mentioned in the comments for the given answer. Here is the sample code from the answer:
Xaml :
<LinearGradientBrush x:Key="MainBrush" StartPoint="0,0.5" EndPoint="1,0.5" >
<GradientBrush.GradientStops>
<GradientStop Color="Blue" Offset="0" />
<GradientStop Color="Black" Offset="1" />
</GradientBrush.GradientStops>
</LinearGradientBrush>
C#:
LinearGradientBrush myBrush = FindResource("MainBrush") as LinearGradientBrush;
myBrush.GradientStops[0].Color = Colors.Red;
推荐答案
您似乎正在尝试进行某种外观设置?
It looks like you're trying to do some sort of skinning?
我建议在单独的文件中包含的资源字典"中定义资源.然后在代码中(App.cs加载默认值,然后在其他位置更改),您可以按以下方式加载资源:
I'd recommend defining the resources in a Resource Dictionary contained in a separate file. Then in code (App.cs to load a default, then elsewhere to change) you can load the resources as so:
//using System.Windows
ResourceDictionary dict = new ResourceDictionary();
dict.Source = new Uri("MyResourceDictionary.xaml", UriKind.Relative);
Application.Current.Resources.MergedDictionaries.Add(dict);
您还可以在App.xaml中定义默认资源字典,然后在代码中很好地将其卸载.
You could also define the default resource dictionary in App.xaml and unload it in code just fine.
使用MergedDictionaries对象更改运行时正在使用的字典.就像魅力一样,可以快速更改整个界面.
Use the MergedDictionaries object to change the dictionary you're using at runtime. Works like a charm for changing an entire interface quickly.
这篇关于WPF:在运行时从App.xaml更改资源(颜色)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!