试试 EventBinder,它允许您将方法直接绑定到任何事件,包括您自己的事件,而无需将方法包装在 ICommand 容器中。
https://github.com/Serg046/EventBinder
https://www.nuget.org/packages/EventBinder
.NET Framework 3.0 + 和 .NET Core 3.0 + 支持
特点:
- 绑定到没有 ICommand 的方法
- 绑定到返回类型的方法
- 绑定到异步方法
- 使用
. 分隔符、属性和字段绑定到嵌套对象
支持
- 传递 int、double、decimal 或 string 类型的用户参数
- 使用
$符号和位置编号传递事件参数($0,$1,
等)
- 将默认
{Binding} 作为参数传递
用法:
public class ViewModel
{
public MetadataViewModel Metadata { get; } = new MetadataViewModel();
public async Task ShowMessage(string msg, decimal centenary, double year)
{
await Task.Delay(0);
MessageBox.Show(msg + centenary + year);
}
public class MetadataViewModel
{
public void ShowInfo(Window window, double windowWidth, ViewModel viewModel, object sender, MouseButtonEventArgs eventArgs)
{
var sb = new StringBuilder("Window width: ")
.AppendLine(windowWidth.ToString())
.Append("View model type: ").AppendLine(viewModel.GetType().Name)
.Append("Sender type: ").AppendLine(sender.GetType().Name)
.Append("Clicked button: ").AppendLine(eventArgs.ChangedButton.ToString())
.Append("Mouse X: ").AppendLine(eventArgs.GetPosition(window).X.ToString())
.Append("Mouse Y: ").AppendLine(eventArgs.GetPosition(window).Y.ToString());
MessageBox.Show(sb.ToString());
}
}
}
绑定:
<Window xmlns:e="clr-namespace:EventBinder;assembly=EventBinder" Name="Wnd">
<Rectangle Fill="LightGray" Name="Rct"
MouseLeftButtonDown="{e:EventBinding ShowMessage, `Happy `, 20m, 20.0 }"
MouseRightButtonDown="{e:EventBinding Metadata.ShowInfo, {Binding ElementName=Wnd},
{Binding ElementName=Wnd, Path=ActualWidth}, {Binding}, $0, $1 }" />
</Window>
或
EventBinding.Bind(Rct, nameof(Rct.MouseLeftButtonDown),
nameof(ViewModel.ShowMessage),
"`Happy `", 20m, 20.0);
EventBinding.Bind(Rct, nameof(Rct.MouseRightButtonDown),
nameof(ViewModel.Metadata) + "." + nameof(ViewModel.Metadata.ShowInfo),
new Binding { ElementName = nameof(Wnd)},
new Binding("ActualWidth") { ElementName = nameof(Wnd) },
new Binding(),
"$0", "$1");