使用没有XAML的基类Style派生控件

时间:2012-01-10 21:11:40

标签: wpf xaml styles code-behind basedon

我正在制作一些封装类,它封装了基类控件的设置细节,但我希望它们使用那里基类的样式。我可以使用以下xaml实现此目的:

<Style TargetType="{x:Type bc:DerviedClass}" BasedOn="{StaticResource {x:Type etk:BaseClass}}"/>

我不想使用xaml,以便客户端程序员不必将此行添加到他的xaml代码中。有没有办法在C#中做到这一点?

由于

2 个答案:

答案 0 :(得分:0)

您应该考虑使用Themes / generic.xaml文件设置样式/主题来设置自定义控件的样式。

  1. 使用generic.xaml时要记住的事项:
    • 资源必须命名为generic.xaml,并且名为Themes(案例事项)
    • AssemblyInfo.cs需要一个ThemeInfo属性
      • [assembly:ThemeInfo(ResourceDictionaryLocation.SourceAssembly,ResourceDictionaryLocation.SourceAssembly)]
  2. 每当有人使用它时,此主题将成为默认主题。

答案 1 :(得分:0)

我找到了解决方法:

Style s = (Style)derivedObj.FindResource(baseType);

if(s != null)
{
    Style derivedStyle = new Style(derivedObj.GetType(), s);
    derivedObj.Style = derivedStyle;
}