上载图片的两种方法:
UI代码:很简单一个Image控件显示加载的图片,一个Button用于文件流方式添加图片
<Window x:Class="拖放添加图片.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" AllowDrop="True"> <Grid Background="#FF8BC957"> <Grid.RowDefinitions> <RowDefinition Height="19*"/> <RowDefinition Height="8*"/> <RowDefinition Height="5*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="149*"/> <ColumnDefinition Width="227*"/> <ColumnDefinition Width="141*"/> </Grid.ColumnDefinitions> <Border Grid.Column="1" BorderBrush="Orange" BorderThickness="3" Background="WhiteSmoke" CornerRadius="5" Margin="5" Drop="Image_Drop_1"> <Grid> <TextBlock Text=" 图片拖动到此添加" TextWrapping="WrapWithOverflow" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="50,76,37,82" Width="124"/> <Image Grid.Column="1" x:Name="phtoSrc" Stretch="Fill" Panel.ZIndex="1"/> </Grid> </Border> <Button Content="...." Width="80" Height="20" Grid.Column="1" Grid.Row="1" Click="Button_Click_1"/> </Grid> </Window>
方法1、将图片拖拽到指定区域添加
Border里面添加Drop事件Image_Drop_1
后台代码:
private void Image_Drop_1(object sender, DragEventArgs e) { string[] fileNames = e.Data.GetData(DataFormats.FileDrop,true) as string[]; if (fileNames.Length > 0) { phtoSrc.Source = new BitmapImage(new Uri(fileNames[0])); } e.Handled = true; }
当将图片拖到Border内即可添加。
方法2:文件方式 点击Button 打开文件对话框选择需要添加的图片即可
对应Button_Click_1的后台代码:
private void Button_Click_1(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); //设置文件类型过滤 dlg.Filter = "图片|*.jpg;*.png;*.gif;*.bmp;*.jpeg"; //禁止多选 dlg.Multiselect = false; // 调用ShowDialog方法显示"打开文件"对话框 Nullable<bool> result = dlg.ShowDialog(); if (result == true) { //获取所选文件名并在FileNameTextBox中显示完整路径 string filename = dlg.FileName; // FileNameTextBox.Text = filename; phtoSrc.Source = new BitmapImage(new Uri(filename)); }
如果添加命名空间Microsoft.Win32则可直接使用OpenFileDialog。