相信大家在阅读WPF相关GitHub开源项目源码时都会看见一串串这种数据
这种Geometry数据就是几何图形数据
为什么要用Geometry数据做图标?
有一种做法是使用ttf字体文件代替,不过使用ttf字体文件会出现下面几个缺点: 1、团队协作不便于管理 2、需要依赖特定平台 3、无法灵活使用 而使用Geometry的话,我们可以将这些几何图形数据存入资源字典ResourceDictionary 通过反射进行灵活使用,团队开发可共同维护
怎么获取Geometry数据?
我们进入 https://HdhCmsTesticonfont.cn/ 官网,找到心仪的图标,点击F12将鼠标放在该图标区域,找到网页元素
Path标签内的d属性即Geometry数据
如何使用Geometry数据
创建资源字典,并加入命名空间
将Geometry数据存入< Geometry x:Key="t_chart" o:Freeze="true" >< /Geometry >标签内 t_chart即资源名称key 可能会有小伙伴注意到了o:Freeze这个属性,下面是MSDN上的原文
A class that derives from Freezable gains the following features: Special states: a read-only (frozen) state and a writable state. Thread safety: a frozen Freezable object can be shared across threads. Detailed change notification: Unlike other DependencyObject objects, a Freezable object provides change notifications when sub-property values change. Easy cloning: the Freezable class has already implemented several methods that produce deep clones. 翻译后: 从Freezable派生的类具有以下功能: 特殊状态:只读(冻结)状态和可写状态。 线程安全:冻结的Freezable对象可以在线程之间共享。 详细的更改通知:与其他DependencyObject对象不同,Freezable对象在子属性值更改时提供更改通知。 易于克隆:Freezable类已经实现了几种产生深层克隆的方法。
随后在App.xaml中加入
<ResourceDictionary Source="Resources/Themes/Geometries.xaml" />
这样我们就可以在全局的XAML代码中通过{StaticResource t_Demo}使用Geometry数据
那么肯定会有小伙伴问了,如果想使用MVVM前后台分离开发怎么办?(在C#代码中动态使用Geometry) 下面是反射加载Geometry的示例 将资源文件存入静态类中
namespace Demo.Resources.Themes { public static class LocalTheme { public static ResourceDictionary Dic = new ResourceDictionary { Source = new Uri(@"Resources/Themes/Geometries.xaml", UriKind.Relative) }; } }
使用资源字典(Geometry)LocalTheme.Dic["t_chart"],t_chart即资源字典中的key值
var chart = new HandyControl.Controls.TabItem() { Header="图表", Content = xamlModel }; chart.SetValue(IconElement.GeometryProperty, (Geometry)LocalTheme.Dic["t_chart"]);
SetValue即设置附加属性 public void SetValue(DependencyProperty dp, object value); 中的value为Geometry
以上就是C# WPF如何反射加载Geometry几何图形数据图标的详细内容,更多关于WPF 反射加载图标的资料请关注其它相关文章!
查看更多关于C# WPF如何反射加载Geometry几何图形数据图标的详细内容...