【问题标题】:I have a Xamarin BindingContext quandary我有一个 Xamarin BindingContext 困惑
【发布时间】:2020-07-21 21:45:45
【问题描述】:

我创建了一个自定义 CheckBox 控件,并在其中添加了 Command/CommandParameter 功能。我使用 Behavior 进行了尝试,但遇到了同样的问题。这是我的 XAML:

`

<ContentPage.Content>
    <CollectionView ItemsSource="{Binding MyShoppingList}" 
                    SelectionMode="None"
                    EmptyView="No items in your Shopping List">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <Grid Padding="0" ColumnDefinitions="30, *, 200">
                    <controls:CheckBoxEx x:Name="CompletedCheckBox"
                                IsChecked="{Binding Completed, Mode=TwoWay}" 
                                Command="{Binding ToggledCommand}"                                    
                                CommandParameter="{Binding .}"
                                HorizontalOptions="Center" 
                                VerticalOptions="Center" />
                    <Label Text="{Binding ItemName}"  Grid.Column="1" HorizontalOptions="StartAndExpand" VerticalOptions="Center"/>
                    <Label Text="{Binding StoreName}" Grid.Column="2" HorizontalOptions="EndAndExpand" VerticalOptions="Center"/>
                </Grid>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
</ContentPage.Content>

`

我的 CollectionView 的 BindingContext 显然是我的 ViewModel; MyShoppingList 是在 ViewModel 中创建的 ObservableCollection。 CheckBox IsChecked 值作为 Completed 属性位于我的模型中。但是,找不到 Command,因为 CollectionView 显然将 BindingContext 从 ViewModel 更改为 Model,因此 Completed、ItemName 和 StoreName 属性已正确绑定。如何将命令与 ViewModel 关联,以便正确发生绑定?该命令的目的是触发数据库更新。这是我看到的运行时错误:

[0:] 绑定:在“ShoppingList.Models.ShoppingListItem”上找不到“ToggledCommand”属性,目标属性:“GLLCustomControls.CheckBoxEx.Command”

【问题讨论】:

    标签: xamarin command custom-controls


    【解决方案1】:

    这样的东西应该可以工作

    Command="{Binding Source={RelativeSource AncestorType={x:Type vm:ShoppingListViewModel}}, Path=ToggledCommand}"
    

    Xamarin 文档有 multiple examples 的更复杂的绑定方案

    【讨论】:

    • 谢谢!我会试试看!嗯....我似乎错过了那个文档...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 2010-12-03
    相关资源
    最近更新 更多