【问题标题】:Simplify resource dictionary addressing in wpf简化 wpf 中的资源字典寻址
【发布时间】:2020-12-11 13:05:46
【问题描述】:

让我这样描述问题 我创建了一个自定义控件,用户可以通过这种方式使用自定义控件

<ResourceDictionary.MergedDictionaries>
  <ResourceDictionary Source="/customControl;component/ThemeResources/Light.xaml"/>
  <ResourceDictionary Source="/customControl;component/ThemeResources.xaml"/>
</ResourceDictionary.MergedDictionaries>

这种方法没有问题,VS IntelliSense 可以识别所有资源。

现在为了更容易使用自定义控件,我使用了以下类:

public class Theme : ResourceDictionary
    {
        public Theme()
        {
            if (DesignerHelper.IsInDesignMode)
            {
                MergedDictionaries.Add(new ResourceDictionary
                {
                    Source = new Uri("pack://application:,,,/customControl;component/ThemeResources/Light.xaml")
                });
                MergedDictionaries.Add(new ResourceDictionary
                {
                    Source = new Uri("pack://application:,,,/customControl;component/ThemeResources.xaml")
                });
            }
            else
            {
                UpdateResource();
            }
        }

        private Uri _source;

        public new Uri Source
        {
            get => DesignerHelper.IsInDesignMode ? null : _source;
            set => _source = value;
        }

        
        public string Name { get; set; }

        private void UpdateResource()
        {
            if (DesignerHelper.IsInDesignMode) return;
                MergedDictionaries.Clear();
                MergedDictionaries.Add(new ResourceDictionary
                {
                    Source = new Uri("pack://application:,,,/customControl;component/ThemeResources.xaml")
                });
                MergedDictionaries.Add(new ResourceDictionary
                {
                    Source = new Uri("pack://application:,,,/customControl.Controls;component/ThemeResources/Light.xaml")
                });
        }

        
    }

现在这样我们就可以使用自定义控件了:

<ResourceDictionary.MergedDictionaries>
  <ui:Theme/>
</ResourceDictionary.MergedDictionaries>

现在的问题是IntelliSense没有检测到所有资源但是如果我们自己编写样式名称,我们可以使用资源。

为什么会出现这个问题? 如何解决这个问题?

【问题讨论】:

    标签: c# wpf custom-controls resourcedictionary mergeddictionaries


    【解决方案1】:

    XAML 智能感知需要在不运行任何代码和/或未构建解决方案的情况下工作。因此它不知道创建 Theme 会用pack://application:,/customControl;component/Themes/Generic.xaml 填充它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      相关资源
      最近更新 更多