JD2022-TU1/main/tools/modules/JD.Guinness.WPF.Module/Behavior/ImageBehavior.cs

73 lines
3.1 KiB
C#

using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media.Imaging;
namespace JD.Guinness.WPF.Module.Behavior
{
public static class ImageBehavior
{
public static readonly DependencyProperty SourceFileProperty = DependencyProperty.RegisterAttached("SourceFile", typeof(string), typeof(ImageBehavior), new PropertyMetadata(OnSourceFileChanged));
public static DelegateCommand<string> OpenExplorerCommand { get; } = new DelegateCommand<string>(OnOpenExplorer, file => !string.IsNullOrEmpty(file));
private static void OnSourceFileChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
{
if (target is Image image)
{
if (args.NewValue is string file && File.Exists(file))
{
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bitmap.UriSource = new Uri(file, UriKind.Absolute);
bitmap.EndInit();
Style style = new Style(typeof(Image), image.TryFindResource(typeof(Image)) as Style);
style.Setters.Add(new Setter(FrameworkElement.ContextMenuProperty, XamlReader.Parse(
@"<ContextMenu
xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:behavior=""clr-namespace:JD.Guinness.WPF.Module.Behavior;assembly=JD.Guinness.WPF.Module""
DataContext=""{Binding PlacementTarget, RelativeSource={RelativeSource Self}}"">
<MenuItem Command=""{x:Static behavior:ImageBehavior.OpenExplorerCommand}"" CommandParameter=""{Binding (behavior:ImageBehavior.SourceFile)}"">
<MenuItem.Header>
<StackPanel Orientation=""Horizontal"">
<TextBlock Text=""{Binding (behavior:ImageBehavior.SourceFile)}"" />
<TextBlock Text="" ("" />
<TextBlock Text=""{Binding Source.PixelWidth}"" />
<TextBlock Text=""x"" />
<TextBlock Text=""{Binding Source.PixelHeight}"" />
<TextBlock Text="")"" />
</StackPanel>
</MenuItem.Header>
</MenuItem>
</ContextMenu>")));
image.Source = bitmap;
image.Style = style;
}
else
{
image.Source = null;
image.Style = null;
}
}
}
private static void OnOpenExplorer(string file)
{
if (File.Exists(file))
{
System.Diagnostics.Process.Start("explorer.exe", $"/select, \"{file}\"");
}
}
public static string GetSourceFile(this DependencyObject obj) => obj.GetValue(SourceFileProperty) as string;
public static void SetSourceFile(this DependencyObject obj, string value) => obj.SetValue(SourceFileProperty, value);
}
}