生活随笔
收集整理的這篇文章主要介紹了
WPF 动态更换图片路径
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
wpf中動態(tài)修改圖片路徑,其實很簡單,有個小伙伴有疑問,綁定了source,為什么不能顯示圖片呢。。。
通過綁定,修改圖片路徑,動態(tài)顯示圖片,效果如下:
圖片支持本地路徑和網(wǎng)絡(luò)路徑,下面就來看看如何做吧:
首先,在項目中創(chuàng)建一個images文件夾,將默認圖片復(fù)制到其中命名為404.jpg
然后:
創(chuàng)建一個窗口,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="動態(tài)修改圖片路徑" 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使用了一個轉(zhuǎn)換器。
窗體后臺代碼如下:
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,實現(xiàn)了INotifyPropertyChanged接口,并且定義了轉(zhuǎn)換器。
這樣就已經(jīng) 實現(xiàn)我們想要的效果啦:
(文中圖片素材,來源于網(wǎng)絡(luò),侵刪)
如果喜歡,點個贊唄~
總結(jié)
以上是生活随笔為你收集整理的WPF 动态更换图片路径的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。