在WPF中使用画笔,模板和样式等资源时,可以将它们指定为StaticResources
<Rectangle Fill="{StaticResource MyBrush}" />
Run Code Online (Sandbox Code Playgroud)
或者作为DynamicResource
<ItemsControl ItemTemplate="{DynamicResource MyItemTemplate}" />
Run Code Online (Sandbox Code Playgroud)
大多数时候(总是?),只有一个工作,另一个将在运行时抛出异常.但我想知道原因:
我假设静态与动态之间的选择并不像看起来那么随意......但我没有看到模式.
检查以下场景(其他可能也适用)[您可以创建项目,只需在右侧文件中复制粘贴代码]:
a - 使用基本内容创建ResourceDictionary(Resources.xaml):
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush Color="Red" x:Key="Test" />
<Style TargetType="{x:Type GroupBox}" x:Key="Test2" >
<Setter Property="Background" Value="Blue" />
</Style>
<Style TargetType="{x:Type TextBlock}" >
<Setter Property="Foreground" Value="Green" />
</Style>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)
b - 创建一个用户控制库,其他人将继承包含基本资源的用户控制库(UserControlBase.cs):
using System.Windows.Controls;
using System;
using System.Windows;
namespace ResourceTest
{
public class UserControlBase : UserControl
{
public UserControlBase()
{
this.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("ResourceTest;component/Resources.xaml", UriKind.RelativeOrAbsolute) });
}
}
}
Run Code Online (Sandbox Code Playgroud)
c - 创建从基础继承的UserControl(UserControl1.xaml):
<ResourceTest:UserControlBase x:Class="ResourceTest.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ResourceTest="clr-namespace:ResourceTest"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="300" >
<Grid>
<GroupBox …Run Code Online (Sandbox Code Playgroud) 为了实现我的应用程序,我使用了很多Blend3.当Blend3想要将资源链接到另一个资源时,它会多次使用链接类型"DynamicResource".正如我所理解的那样(但我可能已经理解得不好),只有当我想在运行时修改链接时,"动态"链接才有意义.在其他情况下,他们使用更多的内存是徒劳的.我不想在运行时修改任何东西,那么问题是:有意义在我的所有应用程序中用"StaticResource"替换"DynamicResource"吗?谢谢!Pileggi
wpf performance dynamicresource expression-blend staticresource