[英]Command-Binding (with RelativeSourceExtension) within a StackLayout using BindableLayout.ItemsSource
I am trying to bind a command (with RelativeSourceExtension) to a button within a StackLayout using BindableLayout.ItemsSource in an Xamarin.Forms App.我正在尝试使用 Xamarin.Forms 应用程序中的 BindableLayout.ItemsSource 将命令(使用 RelativeSourceExtension)绑定到 StackLayout 中的按钮。
Not working version of MyControl.xaml: MyControl.xaml 的不工作版本:
<?xml version="1.0" encoding="UTF-8"?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
...
x:Class="MyApp.Views.MyControl">
<StackLayout Orientation="Horizontal"
BindableLayout.ItemsSource="{Binding Data}">
<Button Command="{Binding Source={RelativeSource AncestorType={x:Type views:MyControl}}, Path=BindingContext.RemoveCommand}"
CommandParameter="{Binding}"
Text="Remove"/>
</StackLayout>
</Grid>
Unfortunately the button is "inactive" and does not let you "click".不幸的是,该按钮处于“非活动状态”并且不允许您“单击”。 The same command binding works fine in a ListView with ItemsSource.相同的命令绑定在带有 ItemsSource 的 ListView 中工作正常。
Working version of MyControl.xaml: MyControl.xaml 的工作版本:
<?xml version="1.0" encoding="UTF-8"?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
...
x:Class="MyApp.Views.MyControl">
<ListView ItemsSource="{Binding Data}"
HasUnevenRows="true">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Button Command="{Binding Source={RelativeSource AncestorType={x:Type views:MyControl}}, Path=BindingContext.RemoveCommand}"
CommandParameter="{Binding}"
Text="Remove"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
Control Usage in MainPage.xmal: MainPage.xmal 中的控制用法:
<Grid BindingContext="{Binding Cart}">
...
<views:MyControl/>
....
</Grid>
Am I generally doing something wrong?我通常做错了什么吗? Or is there a trick to make this work?或者有什么技巧可以使它起作用吗?
You missed using StackLayout.ItemTemplate and after DataTemplate in you xaml. Your button is not wrapped in a good way.您在 xaml 中错过了使用 StackLayout.ItemTemplate 和 DataTemplate 之后。您的按钮没有很好地包装。 That's it.就是这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.