处理Listview中的Xamarin.Forms的切换控制事件

时间:2016-07-01 10:40:02

标签: listview xamarin.forms

我想在我的代码中使用的Toggle按钮添加某种类型的侦听器。由于有多个togglebuttons(每个listview项目一个),因此侦听器应该指定它可能与哪个行相关。我无法在xaml中找到一个很好的方法。这里有人可以帮忙吗?我通过x:Name引用列表,在代码中访问它并尝试通过类型转换来到达切换,然后在按钮上添加一个监听器。这很棘手。关于如何解决这个问题的任何建议?顺便说一句:名字只是a,b,c,d,只是为了隐藏有关我客户的详细信息。

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:me="clr-namespace:simpletest;assemby=simpletest" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="simpletest.WeekView">
    <ContentPage.Content>
        <StackLayout Spacing="10" Padding="8,10">
            <StackLayout Orientation="Horizontal">
                <Label Text="{Binding a}" FontSize="Large" FontAttributes="Bold" />
                <Label Text="{Binding b}" FontSize="Large" FontAttributes="Bold" />
            </StackLayout>
            <me:HideableListView ItemsSource="{Binding c}" SeparatorVisibility="Default">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*" />
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="*" />
                                </Grid.ColumnDefinitions>
                                <StackLayout Grid.Row="0" Grid.Column="0">
                                    <Label Text="{Binding d}" FontSize="Small" HorizontalOptions="Center" />
                                    <Label Text="{Binding e}" FontSize="Small" HorizontalOptions="Center" />
                                </StackLayout>
                                <Switch IsToggled="{Binding f}" Toggled="{Binding g}" HorizontalOptions="Center" Grid.Row="0" Grid.Column="1" />
                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </me:HideableListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

1 个答案:

答案 0 :(得分:0)

使用Switch等额外属性扩展MyItem控件并将其与您的源绑定

<ExtendedSwitch IsToggled="{Binding f}"
 MyItem={Binding e} Toggled="{Binding OnItemToggled}"  />

扩展开关

public class ExtendedSwitch: Switch
    {
        public object MyItem { get; set; }
    }

ToggledEvent

public void OnItemToggled(object sender, ToggledEventArgs e)
        {
            var toggledSwitch = (ExtendedSwitch)sender;
            var item = toggledSwitch.MyItem;
        }