2014-06-24 78 views
2

如何在代碼後面添加下面的資源?如何在代碼隱藏中添加資源

<Window.Resources> 
    <ResourceDictionary> 
     <FrameworkElement x:Key="OpenHand" Cursor="pack://application:,,,/Resources/openhand.cur"/> 
    </ResourceDictionary> 
</Window.Resources> 

回答

5

在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資源化利用,不資源集合到RD

Application.Current.Resources.MergedDictionaries.Add(rd); 
+0

@Vahid,這個答案有用嗎? –

1

試試這個:

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;