WPF 找不到内部用户控件样式



我有一个自定义UserControl,我尝试将其添加到另一个UserControl

<UserControl x:Class="MyProject.Screens.Test"
         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" 
         xmlns:local="clr-namespace:MyProject.Screens"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <Button Style="{StaticResource TestStyle}"/>
</Grid>
<UserControl.Resources>
    <Style x:Key="TestStyle" TargetType="{x:Type Button}">
        <Setter Property="Padding" Value="1"/>
    </Style>
</UserControl.Resources>

它在设计窗口中看起来不错,并且项目编译良好。但是,如果我尝试将此UserControl添加到另一个UserControl

<UserControl x:Class="MyProject.Screens.MainScreen"
         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" 
         xmlns:local="clr-namespace:MyProject.Screens"
         mc:Ignorable="d" 
         d:DesignHeight="1080" d:DesignWidth="1920">
  <Grid>
    <local:Test/>
  </Grid>
</UserControl>

我收到一个错误:

找不到资源"测试样式">

MainScreen.我做错了什么?

将资源声明放在 Content 之前:

<UserControl ...>
    <UserControl.Resources>
        <Style x:Key="TestStyle" TargetType="{x:Type Button}">
            <Setter Property="Padding" Value="1"/>
        </Style>
    </UserControl.Resources>
    <Grid>
        <Button Style="{StaticResource TestStyle}"/>
    </Grid>
</UserControl>

最新更新