ファイルマネージャなどのファイルのリストビューでアイテムのダブルクリックの振る舞いをAttachedPropery化(ビヘイビア)
アイテムがフォルダーの場合、VMの移動フォルダ移動メソッドを呼び出す。
ファイルの場合、関連付けられたアプリで開きます。
ListViewItemDoubleClick.cs
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace Maywork.WPF.Helpers;
public static class ListViewItemDoubleClick
{
public static readonly DependencyProperty EnableProperty =
DependencyProperty.RegisterAttached(
"Enable",
typeof(bool),
typeof(ListViewItemDoubleClick),
new PropertyMetadata(false, OnEnableChanged));
public static void SetEnable(DependencyObject obj, bool value)
=> obj.SetValue(EnableProperty, value);
public static bool GetEnable(DependencyObject obj)
=> (bool)obj.GetValue(EnableProperty);
private static void OnEnableChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not ListView listView) return;
if ((bool)e.NewValue)
{
listView.MouseDoubleClick += OnDoubleClick;
}
else
{
listView.MouseDoubleClick -= OnDoubleClick;
}
}
private static void OnDoubleClick(object sender, MouseButtonEventArgs e)
{
if (sender is not ListView listView) return;
var item = listView.SelectedItem;
if (item is not IFileItem fileItem) return;
// VM取得
if (listView.DataContext is INavigationViewModel<IFileItem> vm)
{
if (fileItem.IsDirectory)
{
vm.Navigate(fileItem);
}
else
{
Process.Start(new ProcessStartInfo
{
FileName = fileItem.Path,
UseShellExecute = true
});
}
}
}
}
IFileItem.cs
INavigationViewModel.cs
Download


コメント