未实现 WPF 自定义控件样式

WPF Custom-Control Style Not Implemented

希望有人能帮帮我。

我正在通过首先制作一个简单的自定义控件来尝试进入 WPF。结构如下所示。

相应的代码是 MainWindow.xaml

<Window x:Class="WPFCustomControl.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:WPFCustomControl.NewFolder1"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">

<StackPanel Grid.Row="1">
    <local:MyCustomControl x:Name = "customControl"                                  
     Content = "Click Me" Width = "70" 
     Margin = "10" Click = "customControl_Click"/>
    <TextBlock Name = "txtBlock"  
     Width = "250" Height = "30"/>
</StackPanel>

Generic.xaml

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFCustomControl.NewFolder1">

<Style TargetType="{x:Type local:MyCustomControl}" BasedOn = "{StaticResource {x:Type Button}}">
    <Setter Property = "Background" Value = "LightSalmon" />
    <Setter Property = "Foreground" Value = "Blue"/>
</Style>

一切正常。 我的问题是当我将 Themes 文件夹移动到 NewFolder1 时,应用程序编译但没有实现样式。

预先感谢您提供有关如何解决此问题的任何建议。

很可能你犯了以下错误, 转到 App.xaml 并添加样式,如下例

<Application.Resources>
        <!-- Resources scoped at the Application level should be defined here. -->
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="NewFolder1/Generic.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
        
    </Application.Resources>

My issue is when I move the Themes folder into the NewFolder1 the application compiles but no Style is implemented.

这是意料之中的。控件的默认样式应位于 themes/generic.xaml 中。这是约定俗成的,框架会在哪里寻找它。

您可以将您的 Style 移动到 NewFolder1 中的另一个 ResourceDictionary,然后修改 themes/generic.xaml 以合并这个:

<ResourceDictionary
    ..>

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/WpfCustomControl;component/NewFolder1/YourDictionary.xaml" />
    </ResourceDictionary.MergedDictionaries>

或者您可以直接在 themes/generic.xaml 中定义您的自定义 Style