WPF中Image控件Source的多种指定方式

本文详细讲解了XAML中图片和字体的加载策略,包括直接路径、资源包引用、App.xaml中的静态/动态资源,以及在C#代码背后的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

XAML中

1、直接绝对路径直接给Source

2、将图片放到项目里面,设置图片为资源;Source写法为:

        图片在另外项目:Source="pack://application:,,,/label里面的Content;component/folder/test.png"
        图片在本项目Source="pack://application:,,,/folder/test.png"

                -- 其中“folder”是文件夹,“label里面的Content”是命名空间,”component“是固定的

3、将图片放到App.xaml中,再StaticResource指定

        App.xaml中:

<Application.Resources>
    <ResourceDictionary>
        <BitmapImage x:Key="AppXamlBitmapImage" UriSource="pack://application:,,,/folder/test.png"/>
        <BitmapImage x:Key="AppXamlBitmapImage2" UriSource="pack://application:,,,/label里面的Content;component/folder/test.png"></BitmapImage>
    </ResourceDictionary>
</Application.Resources>

        然后使用就直接Source="{StaticResouce keyName}",如果需要更换的使用DynamicResource也是可以的

        -- 使用这种方式的图片只能在运行后看到

        

code_behind或VidwModel中

1、最多用就是创建BitmapImage对象

2、使用ImageSourceConverter,这样写得比较复杂

var converter = new ImageSourceConverter();
image1.Source = (ImageSource)converter?.ConvertFromString("D:\\desktop\\tmpp\\二维码.jpg");

image1.Source = new BitmapImage(new Uri("D:\\desktop\\tmpp\\二维码.jpg"));
MessageBox.Show("修改成功");

拓展:字体引入

字体库是.ttf结尾,用的时候就是:pack://application:,,,/项目命名空间;component/路径/#字体名称

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值