简体   繁体   English

在WPF中,如何在设计视图中将样式应用于UserControl?

[英]In WPF, How to apply style to UserControl in design view?

I usually define style and control template in App.xml under tab. 我通常在标签下的App.xml中定义样式和控件模板。 So, while designing the UI, I can see the UI with the style applied in design view in Visual Studio 2008 with .NET3.5. 因此,在设计UI时,我可以看到带有.NET3.5的Visual Studio 2008设计视图中应用样式的UI。

However, in another case, sometimes I make UserControl only project and in that case, there's no App.xml so the UI is appeared as default appearance in design view. 但是,在另一种情况下,有时我仅使UserControl成为项目,在这种情况下,没有App.xml,因此UI在设计视图中显示为默认外观。 It's hard to know actual looking in runtime. 很难知道运行时的实际外观。

Is there any way to apply style to UserControl, too? 有没有办法将样式应用于UserControl? If there's a way to share same style and template between application project and UserControl project, that would be perfect! 如果有一种方法可以在应用程序项目和UserControl项目之间共享相同的样式和模板,那将是完美的!

Please let me know if there's a solution. 请让我知道是否有解决方案。

You can keep your styles in a separate ResourceDictionary in your control project. 您可以将样式保留在控制项目中的单独ResourceDictionary中。 Then you need to Merge Dictionaries in the Resources block at the top of every user control: 然后,您需要在每个用户控件顶部的“资源”块中合并“词典”

<UserControl.Resources>
   <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
         <ResourceDictionary Source="MyControlLibraryStyles.xaml"/>
      </ResourceDictionary.MergedDictionaries>
   </ResourceDictionary>
</UserControl.Resources>

The problem with this approach is of course that you lose any benefit that App-level styles would give you (like styling differently for different applications) because now the styles are all determined by the underlying control. 这种方法的问题当然在于,您将失去应用程序级样式会给您带来的任何好处(例如,为不同的应用程序设置不同的样式),因为现在这些样式都由基础控件确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM