[英]How to add a resource in code-behind
如何在代碼中添加以下資源?
<Window.Resources>
<ResourceDictionary>
<FrameworkElement x:Key="OpenHand" Cursor="pack://application:,,,/Resources/openhand.cur"/>
</ResourceDictionary>
</Window.Resources>
在C#Code-Behind中,你可以這樣做:
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);
試試這個 :
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);
}
var element = Application.Current.MainWindow.Resources["OpenHand"] as FrameworkElement;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.