样式未被拾取 WPF

本文关键字:WPF 样式 | 更新日期: 2023-09-27 18:37:28

我正在尝试在外部DLL中设置样式,该样式将用于定义某些控件的外观。

我有一个在外部 DLL 中定义的资源字典,该字典具有针对文本框的样式:

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="{x:Type TextBox}" x:Key="TextStyle">
        <Setter Property="Text" Value="Moo"/>
    </Style>
</ResourceDictionary>

然后,我在另一个应用程序中引用此构建的 DLL。这有效:

<Window x:Class="HTMLTest.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">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/GX3Resources;component/Resources.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <TextBox Height="23" HorizontalAlignment="Left" Margin="45,217,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Style="{StaticResource TextStyle}"/>
    </Grid>
</Window>

这不会:

<Window x:Class="HTMLTest.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">
        <Window.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="pack://application:,,,/GX3Resources;component/Resources.xaml"/>
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </Window.Resources>
        <Grid>
            <TextBox Height="23" HorizontalAlignment="Left" Margin="45,217,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
        </Grid>
    </Window>

我希望上面的内容能够选择文本样式,因为它是一个文本框,并且样式针对文本框。

样式未被拾取 WPF

如果可以编辑原始样式,则可以通过将 Textbox 的 key 属性设置为目标类型来自动将其用于所有文本框:

<Style TargetType="{x:Type TextBox}" x:Key="{x:Type TextBox}">

如果无法更改样式,请尝试基于它创建另一个样式:

<Style TargetType="{x:Type TextBox}" 
       BasedOn="{StaticResource TextStyle}" 
       x:Key="{x:Type TextBox}">
</Style>