【问题标题】:Creating a Style in code behind在后面的代码中创建样式
【发布时间】:2010-12-16 07:23:05
【问题描述】:

有谁知道如何在后面的代码中创建 wpf 样式,我在网络或 MSDN 文档上找不到任何东西。我已经尝试过了,但它不起作用:

Style s = new Style(typeof(TextBlock));
s.RegisterName("Foreground", Brushes.Green);
s.RegisterName("Text", "Green");

breakInfoControl.dataTextBlock.Style = s;

【问题讨论】:

    标签: c# .net wpf styles code-behind


    【解决方案1】:

    这应该可以满足您的需求:

    Style style = new Style
    {
        TargetType = typeof(Control)
    };
    style.Setters.Add(new Setter(Control.ForegroundProperty, Brushes.Green));
    myControl.Style = style;
    

    【讨论】:

    • 这个答案也是5年前的,所以从那时起事情可能已经改变了
    【解决方案2】:

    您需要在样式中添加 setter,而不是使用 RegisterName。以下代码在 Window_Loaded 事件中将创建一个新的 TextBlock 样式,该样式将成为 Window 中所有 TextBlock 实例的默认样式。如果您希望在一个特定的 TextBlock 上显式设置它,则可以设置该控件的 Style 属性,而不是将样式添加到 Resources 字典。

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Style style = new Style(typeof (TextBlock));
        style.Setters.Add(new Setter(TextBlock.ForegroundProperty, Brushes.Green));
        style.Setters.Add(new Setter(TextBlock.TextProperty, "Green"));
        Resources.Add(typeof (TextBlock), style);
    }
    

    【讨论】:

    • 我也想知道如何做到这一点。感谢这对我有用的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 2011-07-25
    • 2012-01-21
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多