c# - 忽略元数据覆盖?

标签 c# wpf metadata overriding

我做了一个很简单的测试项目:

主窗口.xaml:

<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Test"
        Title="MainWindow" Height="350" Width="525" VerticalAlignment="Center" HorizontalAlignment="Center">

    <StackPanel x:Name="mainPanel" />

</Window>

主窗口.xaml.cs:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Test
{
   public partial class MainWindow : Window
   {
      public MainWindow()
      {
         InitializeComponent();

            MyTextBox myTextBox = new MyTextBox("some text here");

            mainPanel.Children.Add(myTextBox);
      }
   }
}

MyTextBox.cs:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Test
{
    class MyTextBox : TextBox
    {
        static MyTextBox()
        {
            MyTextBox.BackgroundProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata(Brushes.Red));
        }

        public MyTextBox(string Content)
        {
            Text = Content;
        }
    }
}

这个,是为了测试metaData Overriding功能。

现在的问题是:这并没有像我预期的那样工作......

确实,MyTextBox 的背景是白色,而不是红色。

我调查并尝试将其作为自定义类的构造函数:

public MyTextBox(string Content)
{
    Text = Content;
    Background = Brushes.Blue;
    ClearValue(BackgroundProperty);
}

现在这是我在调试时发现的:

在主类中:

MyTextBox myTextBox = new MyTextBox("some text here");

我们进入自定义类的静态构造函数,然后进入实例的构造函数:

Text = Content; >> Background = Red

Background = Brushes.Blue; >> Background = Blue

ClearValue(BackgroundProperty); >> Background = Red again (as expected)

我们回到主类:

mainPanel.Children.Add(myTextBox);

...紧接着这行代码,myTextBox.Background 为白色。

问题:为什么?

为什么我把它添加到主面板时它设置为白色???我找不到任何合乎逻辑的解释......

此外,如果我在执行以下操作的地方添加更多代码:myTextBox.Background = Brushes.Blue; 然后是 myTextBox.ClearValue(MyTextBox.BackgroundProperty); , 它再次变为蓝色然后变为白色,而不是红色。

我不明白。

最佳答案

背景由文本框的默认样式设置。基于Dependency Property Value Precedence红色在#11,而默认样式在#9。蓝色设置将在 #3,因此应该覆盖背景罚款。

您要么必须明确设置背景(就像您使用蓝色画笔所做的那样),要么创建您自己的不设置背景的自定义默认样式。您的默认样式可以基于 TextBox 版本。

关于c# - 忽略元数据覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5431594/

相关文章:

c# - HttpClient GetAsync 和 ReadAsStringAsync 需要反序列化复杂 JSON 响应的一部分

wpf - 如何在资源字典中使用引用转换器

ios - 在哪里可以找到 Apple 的新命令行传送工具 Transporter?

java - 使用 Java 中的 JAudioTagger 从音乐文件获取封面艺术

haskell - 是否有用于将元数据编译到我的包中的 Haskell 模块

c# - 沙盒 paypal 未在查询字符串中返回成功

C# - 当 Dog 是 Animal 的子类时,如何将 List<Dog> 转换为 List<Animal>?

c# - 如何为网络应用成就系统构建基于数据库的规则集?

c# - 无法覆盖包含在 using 语句中的文件

wpf - Caliburn.Micro:不同项目中的 View 和 Bootstrap