// CustomButton.xaml.cs
public partial class CustomButton : UserControl
{
public static readonly DependencyProperty CustomCommandProperty =
DependencyProperty.Register("CustomCommand",
typeof(ICommand),
typeof(CustomButton));
public ICommand CustomCommand
{
get => (ICommand)GetValue(CustomCommandProperty);
set => SetValue(CustomCommandProperty, value);
}
public CustomButton()
{
InitializeComponent();
}
}
步骤4:在ViewModel中使用
csharp
// MainViewModel.cs
public class MainViewModel
{
public ICommand CustomCommand { get; }
public MainViewModel()
{
CustomCommand = new RelayCommand<Tuple<object, object>>(ExecuteCommand);
}
private void ExecuteCommand(Tuple<object, object> parameters)
{
var control = parameters.Item1 as CustomButton;
var eventArgs = parameters.Item2 as MouseEventArgs;
// 实际业务逻辑
MessageBox.Show($"控件位置:{control?.ActualWidth}x{control?.ActualHeight}\n" +
$"点击坐标:{eventArgs?.GetPosition(control)}");
}
}