如何在代码后台中添加资源

3
我该如何在代码后台添加以下资源?
<Window.Resources>
    <ResourceDictionary>
        <FrameworkElement x:Key="OpenHand" Cursor="pack://application:,,,/Resources/openhand.cur"/>
    </ResourceDictionary>
</Window.Resources>
3个回答

6
在C#代码中,您可以这样做:
ResourceDictionary rd = new ResourceDictionary();
FrameworkElement fe = new FrameworkElement() 
{
   Cursor = new Cursor("pack://application:,,,/Resources/openhand.cur") 
};
rd.Add("OpenHand", fe);
Application.Current.Resources = rd;

如果你的资源中有其他ResourceDictionary,你应该将rd添加到Resources中,而不是将Resources设置为rd:
Application.Current.Resources.MergedDictionaries.Add(rd);

2

请尝试以下方法:

 public MainWindow()
        {
            InitializeComponent();
            DataContext = new MainViewModel();
            var res = new ResourceDictionary();
            var frame = new FrameworkElement() 
            {
             Cursor = new Cursor("pack://application:,,,/Resources/openhand.cur") 
            };
            res .Add("framework", frame);
            this.Resources.Add(rd);
        }

-1
var element = Application.Current.MainWindow.Resources["OpenHand"] as FrameworkElement;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接