代码之家  ›  专栏  ›  技术社区  ›  Alan Jackson

如何在运行时创建的wpf控件中重写应用程序样式

  •  0
  • Alan Jackson  · 技术社区  · 15 年前

            Label tb = new Label();
            tb.OverridesDefaultStyle = true;
            tb.Style = null;
            tb.Foreground = new SolidColorBrush(Colors.Black);
            this.Children.Add(tb);
    

    编辑: 由于某种原因,我一直无法让标签工作,但当我切换到文本框时,它工作得很好。

    谢谢你的回复。

    2 回复  |  直到 13 年前
        1
  •  1
  •   itowlson    15 年前

    以下几乎相同的代码适用于我:

      Label l = new Label();
      l.Content = "Fie!!!";
      l.Style = null;
      l.OverridesDefaultStyle = true;  // not required, see below
      l.Foreground = new SolidColorBrush(Colors.Blue);
      ((Grid)Content).Children.Add(l);
    

    之后 设置样式,工作正常。但是如果设置OverridesDefaultStyle 之前 咧嘴笑

        2
  •  1
  •   Tim Cooper    13 年前

    你所要做的就是做好准备 Style null 阻止它继承。然后你可以设置 Foreground 无论你喜欢什么:

    var tb = new TextBlock() { Text = "Hello" };
    tb.Style = null;
    tb.Foreground = Brushes.Blue;
    this.Children.Add(tb);
    

    如果这对你不起作用,我建议完全是另外一回事。

    使用 Brushes.Black SolidColorBrush . 它不仅更干净,刷子也会结冰。您的代码会创建一个未冻结的笔刷,效率较低。你也可以自己打电话冻结它 Freeze() 在刷子上。