我有一个类似这样的自定义控件:
public class CustomControl1 : Control
{
private StackPanel panel;
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
public override void OnApplyTemplate()
{
panel = (StackPanel)GetTemplateChild("root");
panel.Children.Add(new TextBlock { Text = "TextBlock added in the OnApplyTemplate method" });
base.OnApplyTemplate();
}
}
它的控制模板如下:
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<StackPanel Name="root">
<TextBlock>TextBlock added in ControlTemplate</TextBlock>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
然后我在主窗口中使用它:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:app1="clr-namespace:WpfApplication1">
<Grid>
<Grid.Resources>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="Green"></Setter>
</Style>
</Grid.Resources>
<app1:CustomControl1 Foreground="Red">
</app1:CustomControl1>
</Grid>
如果我运行它,它会像这样:
![enter image description here](https://istack.dev59.com/glNz2.webp)
但是我想要一个TextBlock,只有在没有本地值时才遵循样式。
那么为什么这两个TextBlock行为不同,如何获得一个只在没有本地值时遵循样式的TextBlock?
注意:如何使自定义控件内部的TextBlocks不受包含自定义控件的Grid资源中的隐式样式影响。
Grid.Resources
中的样式应该是针对CustomControl1
而不是TextBlock
。<Style TargetType="{x:Type app1:CustomControl1}"> <Setter Property="Foreground" Value="Green"></Setter> </Style>
- anivas