C# xamarin.forms listview的外部itemtemplate中的命令绑定?
我使用mvvm和viewmodel定位器。我使用按钮命令或listview itemtap行为没有问题。但在我的一个页面中,我需要使用外部itemtemplate(参考资料)。在此模板中,我可以毫无问题地绑定标签。但我无法绑定按钮命令,我遇到此错误“无法解析元素上的名称”C# xamarin.forms listview的外部itemtemplate中的命令绑定?,c#,listview,mvvm,xamarin.forms,C#,Listview,Mvvm,Xamarin.forms,我使用mvvm和viewmodel定位器。我使用按钮命令或listview itemtap行为没有问题。但在我的一个页面中,我需要使用外部itemtemplate(参考资料)。在此模板中,我可以毫无问题地绑定标签。但我无法绑定按钮命令,我遇到此错误“无法解析元素上的名称” 这是外部自定义单元格 - 这是带有templateselector的页面(工作正常) 在viewmodel中 public static readonly BindableProperty Tes
这是外部自定义单元格
-
这是带有templateselector的页面(工作正常)
在viewmodel中
public static readonly BindableProperty TestCommandProperty =
BindableProperty.Create("TestCommand", typeof(ICommand), typeof(CustomDonemCell), null);
public ICommand TestCommand => new Command<detay>(testclickevent);
private async void testclickevent(detay item)
{ await NavigationService.NavigateToAsync<detayviewmodel(item.id.ToString());
}
公共静态只读BindableProperty TestCommandProperty=
Create(“TestCommand”、typeof(ICommand)、typeof(CustomDonemCell)、null);
公共ICommand TestCommand=>新命令(testclickevent);
私有异步void testclickevent(detay项)
{await NavigationService.NavigateToAsync您的问题是在何处定义处理程序。您在PageTestViewModel中定义了它,但在xaml中,此命令不是为列表或页面模型定义的。它是为项定义的。因此,您有3个选项。您不必同时定义OnButtonClicked和TestCommand,我只是将其显示为一个选项.如果您同时定义了这两个选项,您将在两个位置被调用(见下文)
在项目中调用
public class testdata
{
public string id { get; set; }
public Command TestCommand
{
get
{
return new Command((o) =>
{
System.Diagnostics.Debug.WriteLine("Item " + o.ToString());
});
}
}
}
要在PageTestViewModel中调用,您需要指定模型的路径。这更复杂。如果前两种方法对您不起作用,请向我发送消息。但这将是一个棘手的问题,因为您的ViewCell xaml位于单独的文件中,因此您无法访问页面名或列表名。我不确定这是否有效设计为在单元格中指定离开顶层模型的处理程序。您可能希望使用我建议的两个处理程序之一,并订阅将从这些处理程序启动的事件
如果您提供示例项目,则更容易快速复制并尝试修复。很抱歉,我使用干净的简单项目复制了此示例,您可以从这里快速查看感谢Yuri,我想从viewmodel调用,尝试使用path,但无法成功。因为当我提供path时(Source={x:Reference Name=mylistView})但它给出了错误,因为listview在页面中,viewcell在资源中。我最好使用你说的第二种方法。谢谢你的帮助。你能描述第三种解决方案吗?我有同样的问题,我想将命令绑定到按钮,按钮位于listview数据模板的另一个文件中,命令在ViewModel中定义。@kaktusas2598你必须使用它绑定路径
public static readonly BindableProperty TestCommandProperty =
BindableProperty.Create("TestCommand", typeof(ICommand), typeof(CustomDonemCell), null);
public ICommand TestCommand => new Command<detay>(testclickevent);
private async void testclickevent(detay item)
{ await NavigationService.NavigateToAsync<detayviewmodel(item.id.ToString());
}
<Button Clicked="OnButtonClicked" Command="{Binding TestCommand}" CommandParameter="{Binding id}" Text="My Button"/>
public partial class CustomCell : ViewCell
{
public CustomCell()
{
InitializeComponent();
}
void OnButtonClicked(object sender, EventArgs args)
{
}
}
public class testdata
{
public string id { get; set; }
public Command TestCommand
{
get
{
return new Command((o) =>
{
System.Diagnostics.Debug.WriteLine("Item " + o.ToString());
});
}
}
}