简体   繁体   English

WPF无法找到内部UserControl样式

[英]WPF cannot locate internal UserControl style

I've got a custom UserControl that I try to add to another UserControl : 我有一个自定义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>

It looks ok in design window, and the projects compiles fine. 在设计窗口中看起来还可以,并且项目可以正常编译。 But if I try to add this UserControl to another UserControl : 但是,如果我尝试将此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>

I recieve an error: 我收到一个错误:

Cannot locate resource "TestStyle" 找不到资源“ TestStyle”

in MainScreen . MainScreen What am I doing wrong? 我究竟做错了什么?

Put the Resources declaration before the 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM