WPF 如何在代码中使用自定义的鼠标资源
如果想要在XAML中使用自定义鼠标很容易,直接在标签中设定 Cursor="/asserts/hand.ani" 即可,
但是如果在代码中使用需要 this.Cursor = new Cursor("鼠标资源路径"); 此处的[鼠标资源路径]需要使用绝对路径,
这就不叫麻烦了。另一种方法就是使用(本人未验证):
StreamResourceInfo sri = Application.GetResourceStream(new Uri("/assets/cursor/hand.ani", UriKind.Relative)); Cursor customCursor = new Cursor(sri.Stream); this.Cursor = customCursor;
感觉都不是很好,后来无意中在网上看到了,一种使用资源字典的实现方式:
//Add to resources: <Window.Resources> <ResourceDictionary> <TextBlock x:Key="CursorGrab" Cursor="Resources/Cursors/grab.cur"/> <TextBlock x:Key="CursorMagnify" Cursor="Resources/Cursors/magnify.cur"/> </ResourceDictionary> </Window.Resources>
// Example of embedded cursor referenced in code: if (selectedTool == "Hand") myCanvas.Cursor = ((TextBlock)this.Resources["CursorGrab"]).Cursor; else if (selectedTool == "Magnify") myCanvas.Cursor = ((TextBlock)this.Resources["CursorMagnify"]).Cursor; else myCanvas.Cursor = Cursor.Arrow;