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接口,并且定义了转换器。
这样就已经 实现我们想要的效果啦:
(文中图片素材,来源于网络,侵删)
如果喜欢,点个赞呗~