gpt4 book ai didi

c# - 忽略元数据覆盖?

转载 作者:太空狗 更新时间:2023-10-30 01:26:14 26 4
gpt4 key购买 nike

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

主窗口.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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com