我有一个自定义控件,在我自己加载了TextBox
的自定义控件中,我在Generic.XAML文件中自定义了TextBox
的样式,但样式未应用,请参考下面的代码
CustomControl.cs
class CustomControl1 : Control
{
public CustomControl1()
{
this.DefaultStyleKey = typeof(CustomControl1);
}
}
Generic.XAML
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:CustomControl">
<Style TargetType="TextBox">
<Setter Property="Foreground" Value="Red"/>
</Style>
<Style TargetType="local:CustomControl1">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomControl1">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<TextBox Width="100" Height="100" Text="Hi"
VerticalAlignment="Center" HorizontalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
MainWindow.XAML
<Page
x:Class="CustomControl.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:CustomControl"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid>
<local:CustomControl1 VerticalAlignment="Center" HorizontalAlignment="Center" Width="200" Height="200"/>
</Grid>
我已在Generic.XAML文件中为TextBox设置了前景色,但未将其设置为TextBox。请参考下图,
如果我在MainWindow.XAML的Page.Resources中为TextBox定制了样式,它的工作正常。但我需要在Generic.XAML中自定义。
对此有何建议?
答案 0 :(得分:1)
有多种解决方案:
Foreground
上设置TextBox
属性。既然你问这个问题,我想你会有多个TextBox
es并且不想重复设置属性。如果某天颜色必须改变,你将会有很多工作。
TextBox
样式添加一个密钥并应用该样式。轻松修复,但如果有多种类型的具有Foreground
属性的控件,则不完美。
<Style x:Key="RedStyle" TargetType="TextBox">
<Setter Property="Foreground" Value="Red"/>
</Style>
<Style TargetType="local:CustomControl1" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomControl1">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<TextBox Width="100" Height="100" Text="Hi" Style="{StaticResource RedStyle}"
VerticalAlignment="Center" HorizontalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Foreground
属性并使用TemplateBinding
这是我最喜欢的解决方法。
<Style TargetType="local:CustomControl1" >
<Setter Property="Foreground" Value="Red" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomControl1">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<TextBox Width="100" Height="100" Text="Hi" Foreground="{TemplateBinding Foreground}"
VerticalAlignment="Center" HorizontalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>