ドラッグアンドドロップ
最終更新:
atachi
-
view
画像ファイルの表示サンプル
エクスプローラーからドラッグアンドドロップでファイルを受け取り、受け取ったファイルが表示可能な画像形式ならば画像を表示します。
画像はImageコントロールを使って表示します。
ソースコード
namespace WpfApplication1 {
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void Grid_DragEnter(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (filePaths.Length >= 1) {
string extension = System.IO.Path.GetExtension(filePaths[0]);
if (extension == ".png" ||
extension == ".jpeg" ||
extension == ".jpg" ||
extension == ".bmp" ||
extension == ".gif") {
e.Effects = DragDropEffects.Link;
}
}
}
}
private void Grid_Drop(object sender, DragEventArgs e) {
string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (filePaths.Length >= 1) {
string extension = System.IO.Path.GetExtension(filePaths[0]);
if (extension == ".png" ||
extension == ".jpeg" ||
extension == ".jpg" ||
extension == ".bmp" ||
extension == ".gif") {
BitmapImage bmp = new BitmapImage(new Uri(filePaths[0]));
image1.Source = bmp;
}
}
}
}
}
<Window x:Class="WpfApplication1.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">
<Grid
Background="#FFEBFFED"
AllowDrop="True" DragEnter="Grid_DragEnter"
Drop="Grid_Drop">
<Image
RenderOptions.BitmapScalingMode="HighQuality"
Height="272"
HorizontalAlignment="Left"
Margin="12,12,0,0"
Name="image1"
Stretch="Uniform"
VerticalAlignment="Top"
Width="234" />
</Grid>
</Window>