如果您希望能够将BindCommand 与自定义视图一起使用,最简单的方法是在名为Command 的视图上拥有ICommand 类型的属性。将OneWayBind 用作Daniel suggested 也很容易,尽管当您习惯于使用BindCommand 进行命令绑定时也很容易忘记这样做。
如果您想使用其他任何东西(事件、手势识别器等...),您可以创建ICreatesCommandBinding 的实现,它定义了命令如何连接到目标对象。因此,您可以执行以下操作:
public class SocketControl : ContentView
{
public static readonly BindableProperty MyCustomCommandProperty = BindableProperty.Create(
nameof(MyCustomCommand),
typeof(ICommand),
typeof(SocketControl));
public ICommand MyCustomCommand
{
get => (ICommand)GetValue(MyCustomCommandProperty);
set => SetValue(MyCustomCommandProperty, value);
}
//...
}
public sealed class SocketControlCommandBinder : ICreatesCommandBinding
{
public IDisposable BindCommandToObject(ICommand command, object target, IObservable<object> commandParameter)
{
var socket = (SocketControl)target;
// get the original value so we can restore it when the binding is disposed...
var originalValue = socket.GetValue(SocketControl.MyCustomCommandProperty);
var disposable = Disposable.Create(() => socket.SetValue(SocketControl.MyCustomCommandProperty, originalValue));
// set the control's command to the view-model's command
socket.SetValue(SocketControl.MyCustomCommandProperty, command);
return disposable;
}
public IDisposable BindCommandToObject<TEventArgs>(ICommand command, object target, IObservable<object> commandParameter, string eventName)
{
/// not shown here ...
return Disposable.Empty;
}
/// <summary>
/// Returns a positive integer when this class supports BindCommandToObject for this
/// particular Type. If the method isn't supported at all, return a non-positive integer.
/// When multiple implementations return a positive value, the host will use the one which
/// returns the highest value. When in doubt, return '2' or '0'
/// </summary>
/// <param name="type">The type to query for.</param>
/// <param name="hasEventTarget">If true, the host intends to use a custom event target.</param>
/// <returns>A positive integer if BCTO is supported, zero or a negative value otherwise</returns>
public int GetAffinityForObject(Type type, bool hasEventTarget)
{
return type.GetTypeInfo().IsAssignableFrom(typeof(SocketControl).GetTypeInfo()) ? 2 : 0;
}
}
一旦你创建了命令绑定器,你需要注册它以便 ReactiveUI 知道如何使用它。在您的 app.xaml.cs(或您创建应用程序的任何位置)中:
Splat.Locator.CurrentMutable.Register(
() => new SocketControlCommandBinder(),
typeof(ReactiveUI.ICreatesCommandBinding));