在 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 ,以避免陈旧错误知识的误导,同时有更好的阅读体验。