我试图在代码中的 TapGestureRecognizer
上设置绑定(bind),但我想不出正确的方法。工作的 xaml 看起来像这样......
<Grid>
<Grid.GestureRecognizers>
<TapGestureRecognizer Command="{Binding LaunchLocationDetailsCommand}"
CommandParameter="{Binding}" />
</Grid.GestureRecognizers>
</Grid>
在 C# 中,它看起来像这样......
var gridTap = new TapGestureRecognizer();
gridTap.SetBinding(TapGestureRecognizer.CommandProperty,
new Binding("LaunchLocationDetailsCommand"));
gridTap.SetBinding(TapGestureRecognizer.CommandParameterProperty,
new Binding(/* here's where I'm confused */));
var grid = new Grid();
grid.GestureRecognizers.Add(gridTap);
我的困惑在于 CommandParameterProperty
的绑定(bind)。在 xaml 中,这只是 {Binding}
没有其他参数。这是如何在代码中完成的?传入 new Binding()
或 this.BindingContext
似乎不起作用。
最佳答案
CommandProperty
绑定(bind)与您所做的相同。
由于您没有将路径传递给某些要使用的属性,因此您的 CommandParameterProperty
不能只创建一个空的 Binding
,因为它会引发异常。
要解决这个问题,您需要按照 Adam 指出的那样指定 Source
属性。
请注意,但是,如果您尝试分配的BindingContext
是 Null
,我怀疑您的情况就是这样,这将< strong>仍然抛出异常。
下面示例中的 Grid
将 BindingContext
设置为 View 模型 (objGrid.BindingContext = objMyView2
)。
然后我们为我们的命令参数创建一个新的绑定(bind),Source
指向我们的 View 模型 (Source = objGrid.BindingContext
)。
如果您运行下面的演示,您将在 Output
窗口中看到一条调试消息,指示来自 View 模型的属性值。
MyView2 objMyView2 = new MyView2();
objMyView2.SomeProperty1 = "value1";
objMyView2.SomeProperty2 = "value2";
objMyView2.LaunchLocationDetailsCommand_WithParameters = new Command<object>((o2)=>
{
LaunchingCommands.LaunchLocationDetailsCommand_WithParameters(o2);
});
Grid objGrid = new Grid();
objGrid.BindingContext = objMyView2;
objGrid.HeightRequest = 200;
objGrid.BackgroundColor = Color.Red;
TapGestureRecognizer objTapGestureRecognizer = new TapGestureRecognizer();
objTapGestureRecognizer.SetBinding(TapGestureRecognizer.CommandProperty, new Binding("LaunchLocationDetailsCommand_WithParameters"));
Binding objBinding1 = new Binding()
{
Source = objGrid.BindingContext
};
objTapGestureRecognizer.SetBinding(TapGestureRecognizer.CommandParameterProperty, objBinding1);
//
objGrid.GestureRecognizers.Add(objTapGestureRecognizer);
支持类:-
MyView2:-
public class MyView2
: ViewModelBase
{
public string SomeProperty1 { get; set; }
public string SomeProperty2 { get; set; }
public ICommand LaunchLocationDetailsCommand_WithParameters { get; set; }
}
启动命令:-
public static class LaunchingCommands
{
public static void LaunchLocationDetailsCommand_WithParameters(object pobjObject)
{
System.Diagnostics.Debug.WriteLine("SomeProperty1 = " + (pobjObject as MyView2).SomeProperty1);
}
}
ViewModelBase:-
public abstract class ViewModelBase
: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string pstrPropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(pstrPropertyName));
}
}
}
关于c# - 在代码隐藏中设置 Xamarin.Forms 绑定(bind) CommandParameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35237556/