如何将byte[]转换为StreamGeometry(WPF绑定场景实现方案咨询)
方案1:适配现有PathIcon写法(适合DisplayIcon存储矢量路径数据场景)
先确认DisplayIcon.BinaryData的存储格式,对应两种实现:
- 若存储的是UTF8编码的路径字符串(即类似
M17.06...的纯路径文本):
var pathStr = System.Text.Encoding.UTF8.GetString(array); return System.Windows.Media.Geometry.Parse(pathStr);
- 若存储的是通过XamlWriter序列化的StreamGeometry二进制数据:
using var ms = new System.IO.MemoryStream(array); return (System.Windows.Media.StreamGeometry)System.Windows.Markup.XamlReader.Load(ms);
方案2:DisplayIcon存储位图数据场景(兼容性更强)
如果自定义图标是png/jpg等位图格式,直接统一用Image控件更合理,不需要编写多套显示逻辑:
第一步:修改Control.xaml
<StackPanel Orientation="Horizontal"> <Image Margin="0,0,5,0" Width="16" Height="16" Source="{Binding , Converter={StaticResource imageConverter}}"/> <TextBlock Text="{Binding}"/> </StackPanel>
第二步:修改转换器逻辑
class TemplateImageConverter : IValueConverter { public object? Convert( object obj, Type targetType, object parameter, CultureInfo culture ) { if (obj is Scripting.Template template) { // 优先加载自定义图标 if( template.DisplayIcon != null ) { var array = template.DisplayIcon.BinaryData; using var ms = new System.IO.MemoryStream(array); var bitmap = new System.Windows.Media.Imaging.BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad; bitmap.StreamSource = ms; bitmap.EndInit(); return bitmap; } // fallback到内置资源图标 else { System.Windows.Media.StreamGeometry? geo = template.Kind switch { DataModel.AttributableEntityIdentifier.DataContainer => Application.Current.FindResource("folder_regular") as System.Windows.Media.StreamGeometry, // 其他类型图标在此补充分支即可 _ => null }; if (geo == null) return null; // 将矢量几何转换为ImageSource return new System.Windows.Media.DrawingImage(new System.Windows.Media.GeometryDrawing(System.Windows.Media.Brushes.Black, null, geo)); } } return null; } public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) { throw new NotImplementedException(); } }
该方案同时支持自定义位图图标、内置矢量图标两种场景,不需要额外编写触发器判断显示逻辑,代码维护成本更低。
内容的提问来源于stack exchange,提问作者Tulesha
相关产品推荐
相关产品推荐

