微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Xamarin列表视图所选项目更改图标颜色

如何解决Xamarin列表视图所选项目更改图标颜色

我已经将滑块菜单实现为ListView,并且可以轻松地将颜色分配给菜单中的任何图标。但是,我试图更改选定的ListView行的颜色(特别是图标)。我尝试使用转换器,但是值永远不会改变。

这是我的xaml:

<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d"
         x:Class="SycretBeauty.Screens.MainMenuMaster"
         Title="Master"
         xmlns:controls="clr-namespace:SycretBeauty;assembly=SycretBeauty"
         xmlns:converters="clr-namespace:SycretBeauty.Converters;assembly=SycretBeauty"
         BackgroundColor="{StaticResource color_menu_item_background}"
         IconImageSource="images/menu.png">

    <StackLayout
    BackgroundColor="{StaticResource color_header_banner_background}">

        <Image
            VerticalOptions="Center"
            HorizontalOptions="FillAndExpand"
            Source="images/bannerVialang.png"
            Margin="0,30,20">
        </Image>

        <controls:SuperListView
            x:Name="MenuItemsListView"
            SeparatorVisibility="Default"
            HasUnevenRows="False"
            Margin="0,0"
            RowHeight="120"
            IsScrollingEnable="False"
            SelectedItem="{Binding SelectedItem}"
            ItemsSource="{Binding MenuItems}"
            BackgroundColor="{StaticResource color_menu_item_background}">

        <d:ListView.ItemsSource>
            <x:Array Type="{x:Type x:String}">
                <x:String>Записаться</x:String>
                <x:String>Акции</x:String>
                <x:String>Уведомления</x:String>
                <x:String>Личный кабинет</x:String>
                <x:String>Контакты</x:String>
                <x:String>Отзывы</x:String>
                <x:String>Галерея</x:String>
                <x:String>Поделиться</x:String>
            </x:Array>
        </d:ListView.ItemsSource>

        <controls:SuperListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Grid
                        VerticalOptions="FillAndExpand"
                        ColumnSpacing="0">

                        <Grid.ColumnDeFinitions>
                            <ColumnDeFinition Width="60"/>
                            <ColumnDeFinition Width="10"/>
                            <ColumnDeFinition Width="*"/>
                        </Grid.ColumnDeFinitions>

                        <StackLayout
                            Grid.Column="0"
                            BackgroundColor="{StaticResource color_menu_item_background}"
                            VerticalOptions="FillAndExpand"
                            HorizontalOptions="FillAndExpand">

                             <controls:IconView
                                VerticalOptions="CenterandExpand"
                                HeightRequest="35"
                                Foreground="{Binding ForegroundColor}"
                                Source="{Binding ImgSource}">
                             </controls:IconView>             
                        </StackLayout>
            
                        <Label
                            Grid.Column="0"
                            Text="{Binding PushCount}" 
                            IsVisible="{Binding PushUnread}"
                            d:Text="23"
                            d:IsVisible="True"
                            HorizontalOptions="FillAndExpand"
                            VerticalOptions="FillAndExpand"
                            HorizontalTextAlignment="Center"
                            VerticalTextAlignment="Center"
                            TextColor="White"/>
            
                        <StackLayout Grid.Column="1"
                            BackgroundColor="{StaticResource color_menu_item_background}"
                            VerticalOptions="CenterandExpand"
                            HorizontalOptions="FillAndExpand">
                        </StackLayout>

                        <Label Grid.Column="2"
                            BackgroundColor="{StaticResource color_menu_item_background}"
                            VerticalOptions="FillAndExpand" 
                            VerticalTextAlignment="Center" 
                            Text="{Binding Title}" 
                            d:Text="{Binding .}"
                            Style="{StaticResource font_menu_item_text}"/>
                    </Grid>
                </ViewCell>
            </DataTemplate>
        </controls:SuperListView.ItemTemplate>
    </controls:SuperListView>
</StackLayout>

这是模型:

    public class MainMenuItem
{
    public MainMenuItem()
    {
        targettype = typeof(MainMenuItem);
    }
    public int Id { get; set; }
    public string ImgSource { get; set; }
    public string Title { get; set; }
    public Type targettype { get; set; }
    public Action ItemSelected { get; set; }
    public string PushCount { get; set; }
    public bool PushUnread { get; set; }
    public Color ForegroundColor { get; set; }
}

这是CS:

public partial class MainMenuMaster : ContentPage
{
    public ListView ListView;
    public AppContext Context { get; set; }

    private float rowHeight;

    public MainMenuMaster()
    {
        InitializeComponent();
        BindingContext = new viewmodel();
        ListView = MenuItemsListView;
        ListView.SizeChanged += ListView_SizeChanged;
    }


    private void ListView_SizeChanged(object sender,EventArgs e)
    {
        var h = ListView.Height;
        rowHeight = (float)(h / 8);
        ListView.RowHeight = (int)rowHeight;
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        (BindingContext as viewmodel).UpdatePushCount(Context.UnreadPushCount);
    }

    public class viewmodel : INotifyPropertyChanged
    { 
        public ObservableCollection<MainMenuItem> MenuItems { get; set; }
        public AppContext Context { get; set; }
        public viewmodel()
        {
            MenuItems = new ObservableCollection<MainMenuItem>(new[]
            {
                new MainMenuItem {
                    Id = 0,ImgSource = "images/signup.png",Title = "Записаться",targettype = typeof(OnlinesignupScreen),ItemSelected = () => {
                        Context.SelectSalonStart(typeof(OnlinesignupScreen));
                    },ForegroundColor = Color.Gray
                },new MainMenuItem {
                    Id = 1,ImgSource = "images/promos",Title = "Акции",targettype = typeof(PromosScreen),ForegroundColor = Color.Gray,},new MainMenuItem {
                    Id = 2,ImgSource = "images/notify",Title = "Уведомления",targettype = typeof(NotificationsScreen),new MainMenuItem {
                    Id = 3,ImgSource = "images/personal",Title = "Личный кабинет",targettype = typeof(PersonalInfoScreen),new MainMenuItem {
                    Id = 4,ImgSource = "images/contacts",Title = "Контакты",targettype = typeof(ContactsScreen),ItemSelected = () => {
                        Context.SelectSalonStart(typeof(ContactsScreen));
                    },new MainMenuItem {
                    Id = 5,ImgSource = "images/Feedback.png",Title = "Отзывы",targettype = typeof(FeedbackScreen),ItemSelected = () => {
                        Context.SelectSalonStart(typeof(FeedbackScreen));
                    },new MainMenuItem {
                    Id = 6,ImgSource = "images/gallery.png",Title = "Галерея",targettype = typeof(galleryScreen),ItemSelected = () => {
                        Context.SelectSalonStart(typeof(galleryScreen));
                    },new MainMenuItem {
                    Id = 7,ImgSource = "images/share",Title = "Поделиться",targettype = typeof(ShareWithFriendScreen),ForegroundColor = Color.Gray
                }
            });

        }

        public void UpdatePushCount(int count)
        {
            MenuItems[2].ImgSource = count > 0 ? "images/badge" : "images/notify";
            MenuItems[2].PushCount = count.ToString();
            MenuItems[2].PushUnread = count > 0;
        }

        #region INotifyPropertyChanged Implementation
        public event PropertyChangedEventHandler PropertyChanged;
        void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            if (PropertyChanged == null)
                return;

            PropertyChanged.Invoke(this,new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }
}

我还有MainMenu(我在其中控制导航)和ListView_onSelected方法,但即使在那儿,我也无法更改图标的颜色。

解决方法

请为INotifyPropertyChanged实现MainMenuItem.cs界面

然后像下面的代码一样更改ForegroundColor属性。

 public class MainMenuItem: INotifyPropertyChanged
    {
        public MainMenuItem()
        {
            TargetType = typeof(MainMenuItem);
        }
        public int Id { get; set; }
        public string ImgSource { get; set; }
        public string Title { get; set; }
        public Type TargetType { get; set; }
        public Action ItemSelected { get; set; }
        public string PushCount { get; set; }
        public bool PushUnread { get; set; }
      


        private Color _foregroundColor;

        public Color ForegroundColor
        {
            get { return _foregroundColor; }
            set
            {
                _foregroundColor = value;

                OnPropertyChanged("ForegroundColor");

            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
        }
    }

对于controls:SuperListViewcontrols:IconView来说我没有什么成就,我用listviewImageButton替换了它,如果选择了该项。我们可以更改ImageButton的背景色进行测试。

  <ImageButton
           Source="{Binding ImgSource}"
           VerticalOptions="CenterAndExpand"
           HeightRequest="35"
           BackgroundColor="{Binding ForegroundColor}"
           >
  </ImageButton>

 private void MenuItemsListView_ItemSelected(object sender,SelectedItemChangedEventArgs e)
        {
            // MainMenuItem mainMenuItem = sender as MainMenuItem;

            MainMenuItem mainMenuItem = viewModel.MenuItems[e.SelectedItemIndex];
            mainMenuItem.ForegroundColor = Color.Red;
        }

此处正在运行GIF。

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。