我有一个WPF解决方案,此解决方案包含3个项目: 1-A内部有多个WPF用户控件的项目 2 - 另一个内部有多个WPF用户控件的项目 3-A项目,其中包含上述2个WPF项目的资源。
如您所知,如果您对此类视图有常见设置 - 使用相同的FontFamily。 - 使用相同的FontSize - 使用相同的FontWeight - 为所有用户控件等使用相同的BackroundBrush。您需要在所有usercontrol标签中声明此setter,如下所示:
<UserControl ....
FontFamily="{DynamicResource MyFontFamily}"
FontSize="{DynamicResource MyFontSize}"
FontWeight="{DynamicResource MyFontWeight}"
Background="{DynamicResource MyAppBgBrush2}"
Width="250" d:DesignHeight="350">
<Grid/>......
但我不想在我的所有UserControl中编写相同的setter。出于这个原因,我决定将此属性设置移动到新的c#文件并在资源项目中找到它。
using System.Windows.Controls;
namespace Resources
{
public class PageBase : UserControl
{
public PageBase()
{
SetResourceReference(FontFamilyProperty, "MyFontFamily");
SetResourceReference(FontSizeProperty, "MyFontSize");
SetResourceReference(FontWeightProperty, "MyFontWeight");
SetResourceReference(BackgroundProperty, "MyAppBgBrush2");
}
}
}
所以,在我的资源项目中,我像这样引用了AssemlyInfo.cs文件:
[assembly: System.Windows.Markup.XmlnsDefinition("http://schemas.sat.com/winfx/2010/xaml/internalresources", "Resources")]
此编辑使我能够声明/创建如下所示的用户控件:
<internalresources:PageBase
xmlns:internalresources="http://schemas.sat.com/winfx/2010/xaml/internalresources">
<Grid>DoWhatEver<Grid/>
<internalresources:PageBase/>
从现在开始,我不必创建其标签开头的usercontrol视图
<UserControl....
,我可以从<internalresources:PageBase
开始......
我的问题是,VisualStudio 2010可以向我展示我所有用户控件的设计表达式混合不能。有趣的是,在VS和Blend中,我的项目编译没有任何错误但是当我尝试在混合中打开我的视图时它说:
- 名称空间“PageBase”在名称空间“http://schemas.sat.com/winfx/2010/xaml/internalresources”
中不存在P.S:引用被正确添加到我的项目中,我的项目适合用混合打开。
答案 0 :(得分:0)
在向其添加新功能或属性时,继承您自己的UserControl是有意义的。在您的情况下,您只想覆盖设计。
您可以通过创建资源XAML(BasePageResources.xaml)并使用Setter标记在那里定义UI属性来实现此目的。
<Style TargetType="Button">
<Setter Property="MinWidth" Value="75"/>
<Setter Property="MinHeight" Value="23"/>
<Setter Property="Margin" Value="11,11,0,0"/>
</Style>
你可以将所有的setter转储到一个文件中,给你的setter键,就像CSS类一样。 然后,在App.xaml中,您可以包含这些文件,以使其在应用程序范围内可访问。
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="BasePageResources.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
应用程序中的所有按钮现在都应该应用您的样式。它比继承更好,WPF绑定比你的解决方案更自然。如果按照预期的方式设计,混合应该可以减少问题。
答案 1 :(得分:0)
我发现了这个问题。问题在于表达混合。如果您的项目设置没有任何PropertyGroup for Debug | AnyCPU,您将遇到此问题。您应该通过文本编辑器将此属性组添加到您的csproj文件中,如下所示:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>