【问题标题】:Can not find resource in custom control template在自定义控件模板中找不到资源
【发布时间】:2012-10-15 13:35:01
【问题描述】:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:CuratioCMS.Client.UI.Controls">
<Style BasedOn="{StaticResource {x:Type Button}}" TargetType="{x:Type local:ImageButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:ImageButton}">
                <StackPanel Height="Auto" Orientation="Horizontal">
                    <Image Width="20"
                           Height="20"
                           Margin="10,4,0,4"
                           Source="{Binding Path=Image,
                                            RelativeSource={RelativeSource TemplatedParent}}"
                           Stretch="Fill" />
                    <TextBlock Margin="5,0,10,0"
                               HorizontalAlignment="Left"
                               VerticalAlignment="Center"
                               FontSize="12"
                               FontWeight="Bold"
                               Foreground="{TemplateBinding Foreground}"
                               Text="{TemplateBinding Label}" />
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

这是 Generic.xaml 中用于 ImageButton 自定义控件的代码。 whit 可以按预期工作,但我不能从 Base button stale 继承,所以这种样式不是从 Button 继承所有基本样式,而是只创建没有任何基本样式的自定义控件,并且就

BasedOn="{StaticResource {x:Type Button}}"

在 VS 内部显示错误 Resource '{x:Type System.Windows.Controls.Button}' is not found

我不知道如何实现所需的样式以及为什么在 Visual Studio 编辑器中显示此错误消息

【问题讨论】:

    标签: wpf xaml custom-controls


    【解决方案1】:

    您正在基于通用按钮样式(位于 Generic.xaml 中)定义样式,然后重新定义样式的模板。这样基本样式就会被覆盖。

    如果你想稍微改变一下样式,你有两个选择:

    选项1:

    1. 为通用按钮样式提供一个键(找到在 Generic.xaml 中使用TargetType="{x:Type Button}" 定义的样式并将x:Key="someName" 添加到其属性中)
    2. 将所有其他按钮(ImageButtons 除外)的样式设置为{StaticResource someName}
    3. 将 ImageButton 样式的 BasedOn 属性设置为 {StaticResource someName}

    选项2:

    1. 您可以复制通用按钮样式
    2. 通过将其 TargetType 设置为 ImageButton 并“不”为其设置任何键来使其通用
    3. 更改所需的部分。

    选项 2 通常是一个更好的解决方案,因为它不需要进行大量更改,但我已经完成了您前段时间想做的事情,但我没有找到任何避免重复样式代码的方法。

    【讨论】:

    • 你能解释一下吗?我同意压倒一切的控制是我在这里所做的,那么在命名默认样式下是什么意思?这不是用户控件,它是自定义控件,所以我想你明白这些是不同的情况
    • 对于我之前的回答中的一些错误,我深表歉意,我对其进行了编辑并添加了更多解释。
    • 好的,但是使用第二个选项,它会询问每个主题相关信息,我将不得不添加对 Aero DLL 的引用并为 Luna 和其他 Windows 主题定义主题,这不是我真正想要的
    • 我还没有看到你遇到了什么,我想最好提交另一个问题来描述这个新问题,并提供更多细节。但是我相信第二种选择是实现正确样式的正确方法。
    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2011-01-20
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多