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

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

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

    我试图在运行时创建一个WPF控件,但我不知道如何让它忽略来自App.xml资源的样式。我曾尝试将样式设置为null,并将OverridesDefaultStyle设置为true,但没有成功。应用程序设置将前景设置为白色,我似乎无法明确地将其设置为其他任何颜色。

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

    编辑:

    2 回复  |  直到 14 年前
        1
  •  1
  •   itowlson    16 年前

    你所要做的就是设置 Style null Foreground 无论你喜欢什么:

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

    如果这对你不起作用,我建议你完全另有打算。

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

        2
  •  1
  •   Tim Cooper    14 年前

    以下几乎相同的代码对我有效:

      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=true设置为 之后 设置样式,它工作正常。但如果设置了“覆盖默认样式” 之前 设置风格,一切都会出错。(不,我不知道为什么会这样! 咧嘴笑

    推荐文章