相信大家在閱讀WPF相關GitHub開源專案原始碼時都會看見一串串這種資料
這種Geometry資料就是幾何圖形資料
為什么要用Geometry資料做圖示?
有一種做法是使用ttf字體檔案代替,不過使用ttf字體檔案會出現下面幾個缺點:
1、團隊協作不便于管理
2、需要依賴特定平臺
3、無法靈活使用
而使用Geometry的話,我們可以將這些幾何圖形資料存入資源字典ResourceDictionary
通過反射進行靈活使用,團隊開發可共同維護
怎么獲取Geometry資料?
我們進入https://www.iconfont.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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/270473.html
標籤:WPF
上一篇:WPF常用控制元件樣式Style ( 控制元件樣式設計靈感來源Element開源組件庫, 本文控制元件實作均為自制不依賴任何控制元件庫 )
