WPF中DrawingImage在设计器及运行时无法显示的问题求助
WPF DrawingImage 无法显示的排查与解决
核心问题分析与修复方案
1. 裁剪区域与坐标平移不匹配
你的DrawingGroup中设置了ClipGeometry="M0,-960 V0 H960 V0 H-960 Z",这个裁剪区域仅覆盖Y轴从-960到0的范围,但后续通过TranslateTransform Y="960"把图形整体移到了Y轴0到960的位置,导致平移后的图形完全超出裁剪范围,被彻底剪掉。
修复方法:
- 调整
ClipGeometry到正确范围,覆盖平移后的图形区域:<DrawingGroup ClipGeometry="M0,0 V960 H960 V0 H0 Z"> - 直接移除不必要的
ClipGeometry(无特殊裁剪需求时)。
2. Image控件未指定尺寸
默认状态下Image没有固定宽高,可能因尺寸为0或过小导致图形不可见,给Image明确设置宽高即可:
<Button> <Image Width="24" Height="24" Source="{StaticResource close_FILL0_wght400DrawingImage}"/> </Button>
3. 资源字典加载验证
若上述修改后仍不显示,先确认资源字典是否正确加载:
- 检查
TestDictionary.xaml与MainWindow.xaml的路径匹配性,若不在同一目录,需调整Source为绝对路径格式:<ResourceDictionary Source="pack://application:,,,/YourProjectName;component/TestDictionary.xaml"/> - 在后台代码中手动获取资源,验证是否能找到:
var drawingImage = FindResource("close_FILL0_wght400DrawingImage") as DrawingImage; // 返回null则说明资源未正确加载
4. 资源引用方式调整
若存在资源加载顺序问题,尝试将StaticResource替换为DynamicResource:
<Image Source="{DynamicResource close_FILL0_wght400DrawingImage}"/>
修改后的完整示例
TestDictionary.xaml(移除裁剪并保留平移):
<DrawingImage x:Key="close_FILL0_wght400DrawingImage"> <DrawingImage.Drawing> <DrawingGroup> <DrawingGroup.Transform> <TranslateTransform X="0" Y="960" /> </DrawingGroup.Transform> <GeometryDrawing Brush="#FF000000" Geometry="F1 M960,960z M0,0z M256,-200L200,-256 424,-480 200,-704 256,-760 480,-536 704,-760 760,-704 536,-480 760,-256 704,-200 480,-424 256,-200z" /> </DrawingGroup> </DrawingImage.Drawing> </DrawingImage>
MainWindow.xaml(指定Image尺寸):
<Window.Resources> <ResourceDictionary Source="TestDictionary.xaml"/> </Window.Resources> <Button> <Image Width="24" Height="24" Source="{StaticResource close_FILL0_wght400DrawingImage}"/> </Button>
内容的提问来源于stack exchange,提问作者Bradley
相关产品推荐
相关产品推荐

