好的,我有一个绑定到viewModel的ViewCell类。如果我创建了一个标签,我可以这样做:
var taskName = new Label()
{
XAlign = TextAlignment.Start,
YAlign = TextAlignment.Start,
FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
FontAttributes = FontAttributes.Bold,
LineBreakMode = LineBreakMode.TailTruncation
};
taskName.SetBinding(Label.TextProperty, "CompanyName");
我想要做的是将对象的值绑定到tapGesture。
var tapGesturePhone = new TapGestureRecognizer ();
var phoneIcon = new Image {
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
Source = "phone.png"
};
phoneIcon.GestureRecognizers.Add (tapGesturePhone);
tapGesturePhone.Tapped += (sender, e) => {
var uri = new Uri("tel:" + );
Device.OpenUri(uri);
};
//uri.setbinding("Uri.text", "PhoneNo")?
关于我如何做到这一点的任何想法?一个解决方案也可以。
我有一个名为ProjectContacts
的模型,ProjectContactsViewModel
设置为BindingContext
。
我的ContentView如下所示:
public ProjectContactsView ()
{
//bind the view model to the context
this.BindingContext = _viewModel;
_list.ItemTemplate = new DataTemplate(typeof(ProjectContactsListCell));
_list.IsGroupingEnabled = true;
_list.GroupDisplayBinding = new Binding("Key");
_list.GroupHeaderTemplate = new DataTemplate(typeof(ProjectContactsListHeaderCell));
_list.HasUnevenRows = true;
}
解决方案
感谢@Sten Petrov,我设法解决了这个问题。我最终不得不在我的ViewCell
private TapGestureRecognizer tapGesturePhone = new TapGestureRecognizer ();
tapGesturePhone.BindingContext = new ProjectContactsViewModel ();
然后我以这种方式将我的TapGestureRecognizer绑定在ViewCell中:
tapGesturePhone.SetBinding<ProjectContactsViewModel> (TapGestureRecognizer.CommandProperty, vm => vm.DialPhoneCommand);
tapGesturePhone.SetBinding<ProjectContactsViewModel> (TapGestureRecognizer.CommandParameterProperty,vm => vm.PhoneNo);
从这里我只需要为ViewModel创建一个Setter and Getter
并在构造函数中初始化Command:
public Command DialPhoneCommand {get;set;}
public string PhoneNo { get {return "http://google.com"; } set{ PhoneNo = value;}}
public ProjectContactsViewModel ()
{
//Assign the dialcommand.
DialPhoneCommand = new Command((phoneNo)=>
Device.OpenUri(new Uri(phoneNo.ToString())));
}
答案 0 :(得分:2)
您可以在Command
中创建ProjectContactsViewModel
并将tapGesture.Command绑定到该地址。
与绑定相同的方式
taskName.SetBinding(Label.TextProperty, "CompanyName");
你可以绑定轻击手势的命令
var tapGesturePhone = new TapGestureRecognizer ();
tapGesturePhone.SetBinding(TapGestureRecognizer.CommandProperty,"DialPhoneCommand");
tapGesturePhone.SetBinding(TapGestureRecognizer.CommandParameterProperty,"PhoneNo");
var phoneIcon = new Image {
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
Source = "phone.png"
};
phoneIcon.GestureRecognizers.Add (tapGesturePhone);
该命令可以在ProjectContactsViewModel
中初始化(为简单起见):
... ProjectContactsViewModel {
public string PhoneNo {get;set;}
public Command DialPhoneCommand {get;set;}
...
public ProjectContactsViewModel(){
DialPhoneCommand = new Command((phoneNo)=>
Device.OpenUri(new Uri("tel:" + phoneNo ));
);
}
}