单击单元格时Listview更改图标

时间:2018-06-07 11:39:26

标签: c# xamarin xamarin.forms

我有一个mastedetailpage并用文本和图标填充菜单我使用listview,我可以显示标题和图标,我想当一个人点击列表视图中的特定单元格并且单元格被选中我想要要改变的图标,我该怎么做?

我已经尝试使用两个图像,一个用于选择图标,另一个用于取消选择图标,但我不知道何时取消选择该单元格,列表视图没有该事件。

感谢。

MasterDetailPage:

<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:viewModels="clr-namespace:Cantina2.ViewModels;assembly=Cantina2"
         xmlns:controls="clr-namespace:ImageCircle.Forms.Plugin.Abstractions;assembly=ImageCircle.Forms.Plugin.Abstractions"
         x:Class="test2.ViewModels.Views.Menu" Title="Menu1" >
<MasterDetailPage.Master>
    <ContentPage Icon="hamburger.png" Title="Menu"  BackgroundColor="White">
        <ContentPage.BindingContext>
            <viewModels:MenuViewModel></viewModels:MenuViewModel>
        </ContentPage.BindingContext>
        <StackLayout Orientation="Vertical">
            <!--left, top, right, bottom-->
            <StackLayout BackgroundColor="#01426A" HeightRequest="130">
                <controls:CircleImage x:Name="CircleImage" Source="{Binding fotoProf}" Aspect="AspectFill" HorizontalOptions="StartAndExpand"  FillColor="Transparent" Margin="15,10,0,0">
                    <controls:CircleImage.WidthRequest>
                        <OnPlatform x:TypeArguments="x:Double">
                            <On Platform="Android, iOS">55</On>
                        </OnPlatform>
                    </controls:CircleImage.WidthRequest>
                    <controls:CircleImage.HeightRequest>
                        <OnPlatform x:TypeArguments="x:Double">
                            <On Platform="Android, iOS">55</On>
                        </OnPlatform>
                    </controls:CircleImage.HeightRequest>
                    <!--<controls:CircleImage.GestureRecognizers>
                        <TapGestureRecognizer
                            Tapped="OnTapGestureRecognizerTapped"
                            NumberOfTapsRequired="1" />
                    </controls:CircleImage.GestureRecognizers>-->
                </controls:CircleImage>
                <Label Text="{Binding NomeColaborador}" Margin="15,10,0,0" TextColor="White">
                    <Label.FontSize>
                        <OnPlatform x:TypeArguments="x:Double">
                            <On Platform="iOS">12</On>
                        </OnPlatform>
                    </Label.FontSize>
                    <Label.FontFamily>
                        <OnPlatform x:TypeArguments="x:String">
                            <On Platform="iOS" Value="OpenSans-Semibold"/>
                            <On Platform="Android" Value="Calibri.ttf#Calibri"/>
                            <On Platform="UWP" Value="Assets\Fonts\OpenSans-Semibold.ttf#Open Sans"/>
                        </OnPlatform>
                    </Label.FontFamily>
                </Label>
                <Label Text="{Binding UsernameFormated}" Margin="15,-5,0,0" FontAttributes="Bold" TextColor="#597CBE" IsVisible="True" Opacity="0.50">
                    <Label.FontSize>
                        <OnPlatform x:TypeArguments="x:Double">
                            <On Platform="iOS">12</On>
                        </OnPlatform>
                    </Label.FontSize>
                    <Label.FontFamily>
                        <OnPlatform x:TypeArguments="x:String">
                            <On Platform="iOS" Value="OpenSans-Semibold"/>
                            <On Platform="Android" Value="Calibri.ttf#Calibri"/>
                            <On Platform="UWP" Value="Assets\Fonts\OpenSans-Semibold.ttf#Open Sans"/>
                        </OnPlatform>
                    </Label.FontFamily>
                </Label>
            </StackLayout>
            <ListView x:Name="NavigationDrawerList" RowHeight="60"
                      SeparatorVisibility="None" BackgroundColor="White"
                      ItemSelected="OnMenuItemSelected" ItemsSource="{Binding menuLista}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout VerticalOptions="FillAndExpand"
                                         Orientation="Horizontal"
                                         Padding="20,10,0,10" Spacing="20">
                                <Image x:Name="ListviewMenuIcon" Source="{Binding IconSource}"
                                       WidthRequest="30"  HeightRequest="30" 
                                       VerticalOptions="Center" />
                                <Label Text="{Binding Title}"
                                       FontSize="Small"
                                       VerticalOptions="Center"
                                       TextColor="#01426A">
                                    <Label.FontFamily>
                                        <OnPlatform x:TypeArguments="x:String">
                                            <On Platform="iOS" Value="OpenSans-Semibold"/>
                                            <On Platform="Android" Value="Calibri.ttf#Calibri"/>
                                            <On Platform="UWP" Value="Assets\Fonts\OpenSans-Semibold.ttf#Open Sans"/>
                                        </OnPlatform>
                                    </Label.FontFamily>
                                </Label>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage>
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
    <ContentPage></ContentPage>
</MasterDetailPage.Detail>

Menu.xaml.cs

public partial class Menu : MasterDetailPage
{


    public ObservableCollection<MenuViewModel> _menuLista;

    public Menu()
    {
        InitializeComponent();

        Settings.Page = "Menu";
        NavigationPage.SetHasNavigationBar(this, false);


        _menuLista = ItemService.GetMenuItems();
        NavigationDrawerList.ItemsSource = _menuLista;



        Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(Inicio_Menu)));

        if (Settings.InicioNavi < 2)
        {
            Navigation.PopPopupAsync();
        }

        var seconds = TimeSpan.FromSeconds(0.7);
        Xamarin.Forms.Device.StartTimer(seconds,
            () =>
            {
                CheckConnection();
                return true;
            });
    }

    public async void CheckConnection()
    {
        try
        {
            if (!CrossConnectivity.Current.IsConnected)

            {
                Settings.InternetCon += 1;

                if (Settings.InternetCon < 2)
                {
                    await Navigation.PushPopupAsync(new ConnectionActivityIndicator());
                }
            }

            else
            {
                if (Settings.InternetCon > 0)
                {
                    Settings.InternetCon = 0;
                    await Navigation.PopPopupAsync();
                    return;
                }

            }
        }
        catch (Exception)
        {

        }
    }

    private async void OnMenuItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        if (CrossConnectivity.Current.IsConnected)
        {
            try
            {
                var item = (MenuViewModel)e.SelectedItem;

                //Obtem o tipo do objeto
                Type pagina = item.TargetType;

                Settings.Semana = "Current";
                Settings.day = "";

                string itemResult = item.IconSource;
                if (itemResult == "Logout.png")
                {
                    Settings.InicioNavi = 0;
                    Settings.Username = "";
                    CrossSecureStorage.Current.DeleteKey("LOGIN");
                    CrossSecureStorage.Current.DeleteKey("パスワード");
                    var vHomePage = new LoginUI();
                    Navigation.InsertPageBefore(vHomePage, this);
                    await Navigation.PopAsync();
                    IsPresented = false;
                }

                else
                {
                    Detail = new NavigationPage((Page)Activator.CreateInstance(pagina));

                    IsPresented = false;
                }
            }
            catch (Exception)
            {
                await Navigation.PopPopupAsync();

                if (Device.RuntimePlatform == Device.Android)
                {
                    XFToast.ShortMessage("Error");

                }


                if (Device.RuntimePlatform == Device.iOS)
                {
                    ToastIOS.ShortIOSMessage("Error");

                }
            }
        }
        else
        {

            if (Device.RuntimePlatform == Device.Android)
            {
                XFToast.ShortMessage("No Connection");

            }


            if (Device.RuntimePlatform == Device.iOS)
            {
                ToastIOS.ShortIOSMessage("No Connection");

            }

        }

    }

由于

1 个答案:

答案 0 :(得分:0)

基于这个例子:

https://acaliaro.wordpress.com/2017/03/18/change-labels-textcolor-in-a-listviews-selecteditem-obviously-in-xamarin-forms/

这是我最好的解决方案。

在列表视图中,我创建了两个图像,一个图像带有源绑定IconSelected,另一个图像带有IconUnSelected,两个图标都添加到列表视图使用的列表中,并为每个图像创建了一个数据编辑器,以通过IValueConverter读取值转换器,如果值是&#34; IconSelected&#34;,图标IconSelected的图像是可见的,如果是&#34; IconUnSelected&#34;图标IconUnSelected的图像可见。

我的列表视图:

<ListView x:Name="NavigationDrawerList" RowHeight="60"
                      SeparatorVisibility="None" BackgroundColor="White"
                      ItemSelected="OnMenuItemSelected" ItemsSource="{Binding menuLista}" SelectedItem="{Binding SelectedItem}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout VerticalOptions="FillAndExpand"
                                         Orientation="Horizontal"
                                         Padding="20,10,0,10" Spacing="20">
                                <Image x:Name="ListIconSelected" Source="{Binding IconSelected}" IsVisible="False" IsEnabled="false" WidthRequest="30"  HeightRequest="30" 
                                       VerticalOptions="Center" >
                                    <Image.Triggers>
                                        <DataTrigger TargetType="Image" Binding="{Binding Selected, Converter={StaticResource cnvInvert}}" Value="IconSelected">
                                            <Setter Property="IsVisible" Value="True" />
                                            <Setter Property="IsEnabled" Value="True" />
                                        </DataTrigger>
                                    </Image.Triggers>
                                </Image>
                                <Image x:Name="ListIconUnSelected" IsEnabled="false" Source="{Binding IconUnSelected}" IsVisible="False" WidthRequest="30"  HeightRequest="30" 
                                       VerticalOptions="Center">
                                    <Image.Triggers>
                                        <DataTrigger TargetType="Image" Binding="{Binding Selected, Converter={StaticResource cnvInvert}}" Value="IconUnSelected">
                                            <Setter Property="IsVisible" Value="True" />
                                            <Setter Property="IsEnabled" Value="True" />
                                        </DataTrigger>
                                    </Image.Triggers>
                                </Image>
                                <Label Text="{Binding Title}"
                                       FontSize="Small"
                                       VerticalOptions="Center"
                                       TextColor="#01426A">
                                    <Label.FontFamily>
                                        <OnPlatform x:TypeArguments="x:String">
                                            <On Platform="iOS" Value="OpenSans-Semibold"/>
                                            <On Platform="Android" Value="Calibri.ttf#Calibri"/>
                                            <On Platform="UWP" Value="Assets\Fonts\OpenSans-Semibold.ttf#Open Sans"/>
                                        </OnPlatform>
                                    </Label.FontFamily>
                                </Label>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

的IValueConverter:

public class SelectedToColorConverter : IValueConverter
{
    #region IValueConverter implementation

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is bool)
        {
            if ((Boolean)value)
                return "IconSelected";
            else
                return "IconUnSelected";
        }
        return "IconUnSelected";
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}