【发布时间】:2018-06-13 07:47:49
【问题描述】:
我正在寻找一种仅限 XAML 的方法来在特定窗口中定义一个未命名的样式,该样式会影响所有 TextBox,甚至是 UserControls 中的那些。
这是一个示例:假设我有一个特定的窗口,我想在其中将所有 TextBox 的 Foreground 属性设置为 Red,包括 UserControls 中包含的那些。我正在尝试这样做:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Width="300"
SizeToContent="Height">
<Window.Resources>
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Style.Setters>
<Setter Property="Foreground" Value="Red"/>
</Style.Setters>
</Style>
</Window.Resources>
<StackPanel Orientation="Vertical">
<TextBox Text="A-Regular"/>
<TextBox Text="B-Bold">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Style.Setters>
<Setter Property="FontWeight" Value="Bold"/>
</Style.Setters>
</Style>
</TextBox.Style>
</TextBox>
<local:MyUserControl/>
<TextBox Text="C-Regular"/>
</StackPanel>
</Window>
使用的 UserControl 如下所示:
<UserControl x:Class="WpfApplication1.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Vertical">
<TextBox Text="Like A, but in UserControl"/>
<TextBox Text="Like B, but in UserControl">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Style.Setters>
<Setter Property="FontWeight" Value="Bold"/>
</Style.Setters>
</Style>
</TextBox.Style>
</TextBox>
</StackPanel>
</UserControl>
结果窗口是:
一切正常,除了文本框“像 B,但在用户控件中”,它是粗体和黑色的。我本来希望看到红色文本,就像在所有其他文本框中一样。
有没有办法让 Window 资源中的未命名样式影响 UserControl 中的所有 TextBox,即使是使用 BasedOn 扩展当前 TextBox 样式的那些?
我正在寻找一种方法,我没有调整我“调用”UserControl 的所有地方(即我在窗口中有<local:MyUserControl/> 的地方)。我也不想修改 UserControl 本身,因为它可能在第三方库中。
【问题讨论】:
-
您还需要在
MyUserControl.xaml中引用Style,就像您在MainWindow.xaml中所做的一样。