【问题标题】:Extending the style of a custom control in xaml在 xaml 中扩展自定义控件的样式
【发布时间】:2012-07-18 19:45:01
【问题描述】:

我正在开发一个 WPF 应用程序,并创建了一个自定义控件,我们将其命名为“CControl”。在我设计应用程序布局的 xaml 文档中。我使用以下方式导入样式:

xmlns:my="clr-namespace:My.Controls"

并且能够很好地使用控件。问题是我想在 CControl 上扩展样式。在资源字典中,我可以设置:

        <Style TargetType="{x:Type my:CControl}">
            <Setter Property="Margin" Value="5 0 5 3" />
        </Style>

这会将样式应用于Control,但不会导入CControl定义的样式,所以我使用:

        <Style TargetType="{x:Type my:CControl}" BasedOn="{StaticResource {x:Type my:CControl}}">
            <Setter Property="Margin" Value="5 0 5 3" />
        </Style>

问题是当我的框架尝试加载 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: 

我尝试了不同的使用 BasedOn 的方法,但没有得到任何工作。任何帮助都会非常有用。

谢谢

乔什

【问题讨论】:

    标签: xaml styles basedon


    【解决方案1】:

    在尝试了一天来扩展自定义控件的样式后,我终于可以让它工作了。您可以通过定义命名空间来使用控件,但如果要扩展控件的样式,则需要包含控件的 ResourceDictionary。我最终添加了:

            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/My.Project;component/Resources/CControl.xaml" />
            </ResourceDictionary.MergedDictionaries>
    

    到我的 WPF Applications Canvas / Xaml 中的 ResourceDictionary。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-26
      • 1970-01-01
      • 2023-03-22
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 2013-07-26
      • 1970-01-01
      相关资源
      最近更新 更多