簡體   English   中英

使用 BindableLayout.ItemsSource 在 StackLayout 中進行命令綁定(使用 RelativeSourceExtension)

[英]Command-Binding (with RelativeSourceExtension) within a StackLayout using BindableLayout.ItemsSource

我正在嘗試使用 Xamarin.Forms 應用程序中的 BindableLayout.ItemsSource 將命令(使用 RelativeSourceExtension)綁定到 StackLayout 中的按鈕。

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>

不幸的是,該按鈕處於“非活動狀態”並且不允許您“單擊”。 相同的命令綁定在帶有 ItemsSource 的 ListView 中工作正常。

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>

MainPage.xmal 中的控制用法:

<Grid BindingContext="{Binding Cart}">
    ...
    <views:MyControl/>
    ....
</Grid>

我通常做錯了什么嗎? 或者有什么技巧可以使它起作用嗎?

您在 xaml 中錯過了使用 StackLayout.ItemTemplate 和 DataTemplate 之后。您的按鈕沒有很好地包裝。 就是這樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM