【问题标题】:Get the Style of a Control {StaticResource {x:Type TextBlock}} in code behind在后面的代码中获取控件 {StaticResource {x:Type TextBlock}} 的样式
【发布时间】:2010-11-27 06:40:16
【问题描述】:

我想在代码后面获取默认的Style 以获得TextBlock,而无需将自定义默认TextBlock Style 添加到XAML 中的资源。

我有这样的方法:

public TextBlock DrawTextBlockAtPoint(string text, Style style)
{
    //...
}

我想提供一个只使用常规 TextBlock Style 的覆盖:

public TextBlock DrawTextBlockAtPoint(string text)
{
   var style = GetDefaultStyleForProperty(TextBlock.StyleProperty);
   DrawTextBlockAtPoint(text, style)
}

有没有办法做到这一点?

【问题讨论】:

    标签: wpf styles default code-behind


    【解决方案1】:

    StaticResource 标记扩展实际上试图为定义键查找资源。如果可以使用 {StaticResource {x:Type TextBlock}} 检索 TextBlock 类型的默认样式,您应该可以使用以下代码在代码中获取它:

    var defaultTextBlockStyle = FindResource(typeof(TextBlock));
    

    当然,这需要在定义了 FindResource 方法的上下文中调用。我在我的主 Window 类中使用了它,它可以工作。

    希望这会有所帮助。

    【讨论】:

    • 这很有帮助:typeof使用声明样式的容器(我的案例是 StackPanel,之前我在 @ 上使用了 FindResource 987654327@,但它不起作用)。
    猜你喜欢
    • 2011-07-08
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    相关资源
    最近更新 更多