尝试使用EventBinder,它将允许您直接将方法绑定到任何事件,包括自己的事件,而无需将方法包装在ICommand容器中。
https://github.com/Serg046/EventBinder
https://www.nuget.org/packages/EventBinder
支持.NET Framework 3.0+、.NET Core 3.0+和Avalonia。
特点:
- 绑定到没有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");