在 WPF 中,如果有一个样式是继承另一个样式,而样式没有使用 TargetType 那么在运行的时候会提示 只能根据带有基类型 IFrameworkInputElement 的目标类型的 Style 样式

在界面添加下面代码

    <Window.Resources>
        <Style x:Key="Style1" TargetType="{x:Type ButtonBase}">
        </Style>
        <Style x:Key="ButtonStyle1" BasedOn="{StaticResource Style1}"></Style>
    </Window.Resources>

    <Grid>
        <ToggleButton Style="{StaticResource ButtonStyle1}"></ToggleButton>
    </Grid>

运行将会提示

只能根据带有基类型“IFrameworkInputElement”的目标类型的 Style。

调用的堆栈

   at System.Windows.Style.Seal()
   at System.Windows.StyleHelper.UpdateStyleCache(FrameworkElement fe, FrameworkContentElement fce, Style oldStyle, Style newStyle, Style& styleCache)
   at System.Windows.FrameworkElement.OnStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
   at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
   at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
   at System.Windows.Baml2006.WpfKnownMemberInvoker.SetValue(Object instance, Object value)
   at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member, Object obj, Object value)
   at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)

原因是 ButtonStyle1 没有设置 TargetType 所以解决方法如下

        <Style x:Key="ButtonStyle1" TargetType="{x:Type ButtonBase}" BasedOn="{StaticResource Style1}"></Style>

给 ButtonStyle1 添加 TargetType 属性

本文代码放在github欢迎小伙伴访问


本文会经常更新,请阅读原文: https://blog.lindexi.com/post/WPF-%E7%BB%91%E5%AE%9A%E7%BB%A7%E6%89%BF%E7%9A%84%E6%A0%B7%E5%BC%8F%E6%8F%90%E7%A4%BA-%E5%8F%AA%E8%83%BD%E6%A0%B9%E6%8D%AE%E5%B8%A6%E6%9C%89%E5%9F%BA%E7%B1%BB%E5%9E%8B-IFrameworkInputElement-%E7%9A%84%E7%9B%AE%E6%A0%87%E7%B1%BB%E5%9E%8B%E7%9A%84-Style-%E6%A0%B7%E5%BC%8F.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

如果你想持续阅读我的最新博客,请点击 RSS 订阅,推荐使用RSS Stalker订阅博客,或者前往 CSDN 关注我的主页

知识共享许可协议 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系

无盈利,不卖课,做纯粹的技术博客

以下是广告时间

推荐关注 Edi.Wang 的公众号

欢迎进入 Eleven 老师组建的 .NET 社区

以上广告全是友情推广,无盈利