【问题标题】:Xamarin Switch Toggled event : get bound item of listXamarin Switch Toggled 事件:获取列表的绑定项
【发布时间】:2018-07-28 18:19:30
【问题描述】:

截至写作时 Mac 上的最新 Xamarin:

<ContentPage.Content>
    <StackLayout>
        <ListView x:Name="ItemsListView" ItemsSource="{Binding Items}" VerticalOptions="FillAndExpand" HasUnevenRows="true" RefreshCommand="{Binding LoadItemsCommand}" IsPullToRefreshEnabled="true" IsRefreshing="{Binding IsBusy, Mode=OneWay}" CachingStrategy="RecycleElement" ItemSelected="OnItemSelected">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <StackLayout Padding="10">
                                <Label Text="{Binding Summary}" LineBreakMode="NoWrap" Style="{DynamicResource ListItemTextStyle}" FontSize="Medium" />
                                <Label Text="{Binding Reporter}" LineBreakMode="NoWrap" Style="{DynamicResource ListItemDetailTextStyle}" FontSize="Micro"  />
                            </StackLayout>
                            <StackLayout Orientation="Horizontal" HorizontalOptions="EndAndExpand">
                                <Label Text="{Binding Start}" FontSize="Medium" VerticalOptions="Center"/>
                                <Switch IsToggled="{Binding Result}" Toggled="Handle_Toggled"  VerticalOptions="Center"/>
                            </StackLayout>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage.Content>

如何将绑定的项目获取到 ListView 中的 Switch 控件。该项目位于由 ViewModel 提供的绑定到 ListView 的项目列表中。您可以在不选择行的情况下“切换”项目的切换。

void Handle_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e)
{
    // In this event handler, how do I get the bound item from the ListView?? 
}

【问题讨论】:

    标签: xamarin.forms binding


    【解决方案1】:

    通常,您需要做的是对项目类中属性“结果”的更改做出反应,并将您的逻辑排除在 Page 类之外。 如果需要在事件中处理,可以这样处理:

    void Handle_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e)
    {
        var switch = sender as Switch;
        var item = switch.Parent.BindingContext as ItemViewModel;
    }
    

    将 ItemViewModel 替换为您的项目类型。

    【讨论】:

    • 谢谢 - 了解 PropertyChangedEvent;那讲得通。在这种情况下,如果用户切换开关时项目的某些方面处于某种状态,我需要实际拉出项目详细信息页面。就我而言 - 项目的“列表”由 ViewModel 提供,因此 switch.BindingContext 是实际的数据项目记录。
    • @Hicham 如何在 MVVM 模型中获得类似的结果?
    • @niketan 这取决于您的解决方案,但通常使用两种方法完成:1. Switch 上的两种方式数据绑定。 2.将toggling事件传递给ItemViewModel
    猜你喜欢
    • 2017-04-25
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    相关资源
    最近更新 更多