wpf - TargetType 与元素类型不匹配

标签 wpf xaml

我为ButtonTargetType定义了一个简单的buttonStyle;但将样式设置为按钮会产生异常(exception)。

<Window>
    <Window.Resources>
        <Style x:Key="buttonStyle" TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Magenta"/>
        </Style>
    </Window.Resources>
    <StackPanel Orientation="Horizontal">
        <Button Content="1" FocusVisualStyle="{StaticResource buttonStyle}"/>
    </StackPanel>
</Window>

Additional information: 'Button' TargetType does not match type of element 'Control'.

<小时/>

此外,将 TargetType 设置为 Control 可以消除运行时错误,但按钮的视觉样式在获得 Focus 时不会改变>.

<小时/>

样式在设置为 Button.Style 时有效

<小时/>

编辑 我有两个具体问题:

  1. 我同意 FocusVisualStyleFrameworkElementFrameworkContentElement 的属性,但为什么设置它时出错在按钮上,尽管 Style 是一个namedstyle而不是typedstyle

  2. 为什么 FocusVisualStyle 未在 Button 上呈现? Button.FocusVisualStyle 是否在内部被任何更高优先级的值(例如模板、触发器或模板触发器)覆盖?

最佳答案

FocusVisualStyle 允许您在控件获得焦点时向用户提供视觉反馈。例如,添加一个看起来像控件边框的矩形

Style 是控件本身的外观和感觉。一切都解释清楚了here .

FocusVisualStyle 不是 Button 本身的样式,而是 Button 获得焦点时的样式。

参见here了解更多信息。

我认为你想要的是一个触发器

<Style x:Key="buttonStyle" TargetType="{x:Type Button}">
    <Style.Triggers>
        <Trigger Property="IsFocused" Value="True">
            <Setter Property="Background" Value="Magenta"/>
        </Trigger>
    </Style.Triggers>
</Style>

然后,您可以设置 ButtonStyle,如下所示:

<Button Style="{StaticResource buttonStyle}" ... />

关于wpf - TargetType 与元素类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30804752/

相关文章:

.net - 如何将非硬编码的内容传递给转换器参数

.net - 样式化嵌套 ListBox 的 ListBoxItem [WPF]

.net - 网格与 Canvas

wpf - XAML - 如何在 StackPanel 中将控件彼此对齐

c# - 如何将 wpf 调度程序转换为 winforms

wpf - 如何编写 WPF 触发器来更改文本 block 悬停上的光标

c# - 经典 Windows 主题和 Aero 中 WPF 控件的大小

WPF:将一个组件的高度绑定(bind)到另一个组件的高度

c# - WPF圆形边框按钮,响应单击颜色变化

silverlight - 在 XAML 中绑定(bind)图像源