WPF 动态更换图片路径

wpf中动态修改图片路径,其实很简单,有个小伙伴有疑问,绑定了source,为什么不能显示图片呢。。。

通过绑定,修改图片路径,动态显示图片,效果如下:

图片支持本地路径和网络路径,下面就来看看如何做吧:

首先,在项目中创建一个images文件夹,将默认图片复制到其中命名为404.jpg

然后:

创建一个窗口,xaml代码如下:

<Window x:Class="WxDemo.ChageImageDemo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WxDemo"
        mc:Ignorable="d"
        Background="LightBlue"
        Title="动态修改图片路径" Height="450" Width="800">
    <Window.Resources>
        <local:StringToBitmapImageConverter x:Key="imageConverter"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="40"/>
        </Grid.RowDefinitions>
        <Image Source="{Binding ImagePath,Converter={StaticResource imageConverter}}" Grid.Row="0"/>
        <DockPanel Grid.Row="1">
            <TextBlock Text="输入图片路径:" DockPanel.Dock="Left" VerticalAlignment="Center" FontSize="18"/>
            <TextBox Text="{Binding ImagePath,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 BorderThickness="1" BorderBrush="Black" VerticalContentAlignment="Center"
                 FontSize="18"  Background="LightBlue"/>
        </DockPanel>


    </Grid>
</Window>


有一个图片,和一个文本框,绑定了同一个string类型的ImagePath属性,Source使用了一个转换器。

窗体后台代码如下:

using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;


namespace WxDemo
{
    public partial class ChageImageDemo : Window, INotifyPropertyChanged
    {
        public ChageImageDemo()
{
            InitializeComponent();
            DataContext = this;
        }


        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string name)
{
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
        private string _imagePath= @"D:\bizhi\清纯\10-1.jpg";


        public string ImagePath
        {
            get { return _imagePath; }
            set
            {
                _imagePath = value;
                OnPropertyChanged(nameof(ImagePath));
            }
        }
    }
    public class StringToBitmapImageConverter : System.Windows.Markup.MarkupExtension, IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
            string path = value?.ToString();
            if(string.IsNullOrEmpty(path)) 
                return new BitmapImage(new Uri("/images/404.jpg",UriKind.Relative));
            try
            {
                return new BitmapImage(new Uri(path));
            }
            catch (Exception)
            {
                return new BitmapImage(new Uri("/images/404.jpg",UriKind.Relative));
            }
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
            throw new NotImplementedException();
        }
        public override object ProvideValue(IServiceProvider serviceProvider)
{
            return new StringToBitmapImageConverter();
        }
    }
}


后台代码里面指定了DataContext,实现了INotifyPropertyChanged接口,并且定义了转换器。

这样就已经 实现我们想要的效果啦:

(文中图片素材,来源于网络,侵删)

如果喜欢,点个赞呗~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值