WPF - 将样式从另一个程序集应用到用户控件

时间:2016-10-16 08:59:02

标签: wpf xaml styles controls .net-assembly

我有一个包含多个项目的解决方案:

  • 申请
  • User Control Library
  • Class Library

我想将Style中包含的Class Library应用于User Control中包含的User Control Library。问题是我无法引用App.xaml中的Style,就像我对主应用程序一样,因为我正在使用User Control Library,我不知道如何让{ {1}}使用User Control Class Library。我添加了对Styles的{​​{1}}引用,但是当我为Class Library设置User Control Library时,我找不到我想要的Style。那么目前的做法是什么?

1 个答案:

答案 0 :(得分:0)

您可以使用以下class library。您只需将这两个文件添加到public abstract class StyleRefExtension : MarkupExtension { #region Fields /// <summary> /// Property for specific resource dictionary /// </summary> protected static ResourceDictionary RD; #endregion #region Properties /// <summary> /// Resource key which we want to extract /// </summary> public string ResourceKey { get; set; } #endregion #region Public Methods /// <summary> /// Overriding base function which will return key from RD /// </summary> /// <param name="serviceProvider">Not used</param> /// <returns>Object from RD</returns> public override object ProvideValue(IServiceProvider serviceProvider) { return ProvideValue(); } public object ProvideValue() { if (RD == null) throw new Exception( @"You should define RD before usage. Please make it in static constructor of extending class!"); return RD[ResourceKey]; } #endregion }

WpfRdExt / StyleRefExtension.cs

StyleRefExt.cs

实施为public class StyleRefExt : StyleRefExtension { #region Constructors static StyleRefExt() { RD = new ResourceDictionary { Source = new Uri("pack://application:,,,/YourNamespace;component/Styles/YourStyle1.xaml")}; RD.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri( "pack://application:,,,/YourNamespace;component/Styles/YourStyle2.xaml")}); } #endregion }

Resources

然后,您可以使用x:Key="YourKey" class libraryuser control library标记的<TextBox Style="{YourNamespace:StyleRefExt ResourceKey=YourKey}" /> ,如下所示:

{{1}}

对我来说这很好用,我也用它。

相关问题