【问题标题】:How to add ResourceDictionary programmatically?如何以编程方式添加 ResourceDictionary?
【发布时间】:2019-03-08 02:58:06
【问题描述】:

我是 C# WPF 的新手,只能依靠互联网来继续我的项目。目前,我在添加 ResourceDictionary 名称 ThumbStyle.xaml 时遇到问题,该名称包含一些需要在名为 LineAdorner.cs 的类文件中访问的样式。

来自 ThumbStyle.xaml 的代码:

<Style x:Key="LineMoveThumbStyle" TargetType="{x:Type Thumb}">
    <Setter Property="Cursor" Value="SizeAll"></Setter>
    <Setter Property="Width" Value="7"></Setter>
    <Setter Property="Height" Value="7"></Setter>
</Style>

<Style x:Key="LineResizeThumbStyle" TargetType="{x:Type Thumb}">
    <Setter Property="Width" Value="7"></Setter>
    <Setter Property="Height" Value="7"></Setter>
    <Setter Property="Cursor" Value="Hand"></Setter>
</Style> 

来自 LineAdorner.cs 的代码:

this._moveThumb = new MoveThumb();
this._moveThumb.Style = (Style)Application.Current.FindResource("LineMoveThumbStyle");
this._visuals.Add(this._moveThumb);

this._startThumb = new LineStartPointThumb(_adornedLine);
this._startThumb.Style = (Style)Application.Current.FindResource("LineResizeThumbStyle");
this._visuals.Add(this._startThumb);

this._endThumb = new LineEndPointThumb(_adornedLine);
this._endThumb.Style = (Style)Application.Current.FindResource("LineResizeThumbStyle");
this._visuals.Add(this._endThumb);

如上所示,我尝试使用“FindResource”方法将样式从 Thumbsytle.xaml 检索到 LineAdorner.cs。然而系统给我一个错误:

System.Windows.ResourceReferenceKeyNotFoundException occurred.
Message='LineMoveThumbStyle' resource not found.

我缺少一些步骤吗?希望任何人都可以帮助我解决这个问题。非常感谢。

【问题讨论】:

  • 您的 LineResizeThumbStyle 已添加到哪个资源字典中?可能会在这里找到答案:stackoverflow.com/questions/618648/…
  • 我猜ThumbStyle.xaml 没有合并到LineAdorner.cs 的可用资源中。您可以像这样添加它:ResourceDictionary r = new ResourceDictionary(); r.Source = new Uri("Uri/To/your/xaml"); Application.Current.Resources.MergedDictionaries.Add(r);
  • 为什么要以编程方式添加资源字典而不是在 app.xaml 资源中引用它?
  • 傻我.. 谢谢大家的帮助.. 最后我注意到我没有将它们添加到 app.xaml 资源中.. 大声提醒 @grek40.. 谢谢队友

标签: c# wpf xaml


【解决方案1】:

我不太明白你想做什么,但这对你有帮助吗? 首先,将您的资源放在名为 Resources 的文件夹中,然后:

            var rsrc = "Resources/ThumbStyle.xaml";
            var currentRsrc = new Uri(rsrc, UriKind.RelativeOrAbsolute);
            Application.Current.Resources.MergedDictionaries[0] = new ResourceDictionary() { Source = currentRsrc };

祝你好运!

【讨论】:

    【解决方案2】:
    Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary
    {
    Source = new Uri("/DLLName;component/subFolder/dictionary.xaml", UriKind.RelativeOrAbsolute)
    });
    

    【讨论】:

      猜你喜欢
      • 2017-11-24
      • 2021-07-31
      • 2011-01-03
      • 2015-05-01
      • 2016-11-23
      • 2012-09-16
      • 2014-07-03
      • 2016-04-02
      • 1970-01-01
      相关资源
      最近更新 更多