jgr*_*oll 1 xaml styles basedon
我正在开发一个 WPF 应用程序,并创建了一个自定义控件,我们将其称为“CControl”。在我设计应用程序布局的 xaml 文档中。我使用以下方式导入样式:
xmlns:my="clr-namespace:My.Controls"
Run Code Online (Sandbox Code Playgroud)
并且我能够很好地使用该控件。问题是我想扩展 CControl 上的样式。在资源词典中,我可以设置:
<Style TargetType="{x:Type my:CControl}">
<Setter Property="Margin" Value="5 0 5 3" />
</Style>
Run Code Online (Sandbox Code Playgroud)
这会将样式应用于 Control,但不会导入 CControl 定义的样式,因此我使用:
<Style TargetType="{x:Type my:CControl}" BasedOn="{StaticResource {x:Type my:CControl}}">
<Setter Property="Margin" Value="5 0 5 3" />
</Style>
Run Code Online (Sandbox Code Playgroud)
问题是当我的框架尝试加载 xaml 时,出现以下异常:
System.Windows.Markup.XamlParseException occurred
Message='Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '18' and line position '54'.
Source=PresentationFramework
LineNumber=18
LinePosition=54
StackTrace:
at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, Boolean skipJournaledProperties, Uri baseUri)
at System.Windows.Markup.XamlReader.Load(XamlReader xamlReader, ParserContext parserContext)
at System.Windows.Markup.XamlReader.Load(XamlReader reader)
at FATPOT.Whiteboard.Report.Show() in C:\...\Report.cs
InnerException:
Message=Cannot find resource named 'My.Controls.CControl'. Resource names are case sensitive.
Source=PresentationFramework
StackTrace:
at System.Windows.StaticResourceExtension.ProvideValueInternal(IServiceProvider serviceProvider, Boolean allowDeferredReference)
at System.Windows.StaticResourceExtension.ProvideValue(IServiceProvider serviceProvider)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CallProvideValue(MarkupExtension me, IServiceProvider serviceProvider)
InnerException:
Run Code Online (Sandbox Code Playgroud)
我尝试过使用 BasedOn 的不同方法,但没有任何效果。任何帮助都会非常有用。
谢谢
乔什
经过一天的尝试来扩展自定义控件的样式后,我终于能够让它工作了。您可以通过定义命名空间来使用控件,但如果要扩展控件的样式,则需要包含控件的 ResourceDictionary。我最终添加:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/My.Project;component/Resources/CControl.xaml" />
</ResourceDictionary.MergedDictionaries>
Run Code Online (Sandbox Code Playgroud)
到我的 WPF 应用程序画布/Xaml 中的 ResourceDictionary。