当我发现这个奇怪的现象时,我正在制作一个 UserControl。如果我使用 C# 代码在 UserControl 的模板中放置一个 GroupBox,然后在 GroupBox 上进行任何 SetResourceReference 调用,那么 GroupBox 突然继承了 TemplateParent(我的 UserControl)的前景。
到目前为止,我已经找到了针对这种情况的以下要求:
- UserControl 基本类型无关紧要
- 受影响的模板子必须是 GroupBox(但不一定是第一个模板子)
- GroupBox 的前景可以在模板中显式设置,覆盖继承
- 必须使用来自 GroupBox 的某种引用调用
- 只有 Foreground 属性似乎受到影响
这是我的示例代码:
MainWindow.xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="350">
<Window.Resources>
<Thickness x:Key="TestPadding">5</Thickness>
<Style TargetType="{x:Type GroupBox}">
<Setter Property="Foreground" Value="Red" />
<Setter Property="Background" Value="Orange" />
</Style>
</Window.Resources>
<Grid>
<my:TestControl Foreground="Blue" Background="Purple" />
</Grid>
</Window>
测试控制.cs:
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Markup;
namespace WpfApplication1
{
public class TestControl : UserControl
{
public TestControl()
{
FrameworkElementFactory group = new FrameworkElementFactory(typeof(GroupBox));
group.SetValue(GroupBox.ContentProperty, "My Child");
group.SetResourceReference(GroupBox.MarginProperty, "TestPadding");
this.SetValue(TestControl.TemplateProperty, new ControlTemplate(typeof(TestControl)) { VisualTree = group });
}
}
}
你们怎么看,这是我应该向微软报告的错误吗?