使用ObservableCollection和INotifyPropertyChanged的正确方法

时间:2018-07-27 07:11:45

标签: c# listview xamarin xamarin.forms

我有一个ListView,要根据接收到的String填充一些项目。我目前有一个Listview,在其中我“手动”添加了一些条目以尝试熟悉 INotifyPropertyChanged ObservableCollection 的概念。我想要做的是有一个图像,当点击ListView项时(它将仅针对该特定点击的ListView项)会发生变化。目前,我只能通过将Image用作ImageButton(Image Tapped Event)来使其工作。在ListView中一起使用这两个属性的正确方法是什么?

我只使用Xamarin和C#不到两个星期,所以如果答案或建议非常简单,我深表歉意。任何帮助/建议或示例,将不胜感激。提前致谢。

“我的中继”类(具有INotifyPropertyChanged)如下:

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Runtime.CompilerServices;
 using System.Text;


 namespace Socket.Models
 {


    public class Relays : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged([CallerMemberName] string name =     
           "")
    {
        PropertyChanged?.Invoke(this, new         
        PropertyChangedEventArgs(name));
    }

    //public string ImageUrl { get; set; }    // The source of the 
                                             Image in the Listview 

    public int ID { get; set; }

    private string _Name;

    public string Name                      // The name of the item in 
                                               the ListView
    {
        get
        {
            return _Name;
        }
        set
        {
            if (_Name != value)
            {
                _Name = value;

                OnPropertyChanged();
            }
        }
    }

    private string _ImageUrl;

    public string ImageUrl                      // The name of the 
                                         Image in the ListView
    {
        get
        {
            return _ImageUrl;
        }
        set
        {
            if (_ImageUrl != value)
            {
                _ImageUrl = value;

                OnPropertyChanged();
               }
           }
       }

   }

 }

RelayControl.xaml.cs类(带有ObservableCollection)如下:

 using Socket.Models;
 using System;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.ComponentModel;
 using System.Linq;
 using System.Runtime.CompilerServices;
 using System.Text;
 using System.Threading.Tasks;
 using Xamarin.Forms;
 using Xamarin.Forms.Xaml;

 namespace Socket
 {
     [XamlCompilation(XamlCompilationOptions.Compile)]

     public partial class RelayControl : ContentPage
     {
         public Boolean RelayOn=false;                   // Used to                
                                                    check the State
         public string RelayName;                        // Used to 
                                               test the name change
         public string Images;                           // Used to 
                                                   change the Image
         public int RelayID;

         public RelayControl()
         {
             InitializeComponent ();
             Images= "ryno.jpg";
             RelayName = "Cool";
             loadSampleData();
             this.BindingContext = new Relays();         // Binding the 
                                                    Listview items

             var neg = lstView.BindingContext as Relays;

           //RelayOn = neg.isOn;                        // Assign the 
                            Binding OnProperty to the Boolean Variable
             RelayName = neg.Name;

             Images = neg.ImageUrl; 

             RelayID = neg.ID;
         }

         private void loadSampleData()
         {
        // Create sample data

             ObservableCollection<Relays> listRelays = new      
                               ObservableCollection<Relays>();

             listRelays.Add(new Relays { Name = "Relay " + 0, ImageUrl 
                                              = "ryno.jpg", ID = 0 });
             listRelays.Add(new Relays { Name = "Relay " + 1, ImageUrl 
                                    ="ryno.jpg", ID = 1 }); // num = i
             listRelays.Add(new Relays { Name = RelayName, ImageUrl = 
                                                    Images, ID = 2 });

             lstView.ItemsSource = listRelays;                 
         }

         public class MyListItemEventArgs : EventArgs
         {
             public Relays MyItem { get; set; }

             public MyListItemEventArgs(Relays item)
             {
                 this.MyItem = item;
             }
         }

         private void ImageCell_Tapped(object sender, 
                                      MyListItemEventArgs e)
         {
             var item = e.MyItem;

             if (item == null) return;

             if (item.ID == 2)
             {
                 if (RelayOn == true)
                 {
                     RelayName = "On";
                     Images = "on.jpg";
                     RelayOn = false;
                 }
                 else
                 {
                     RelayName = "OFF";
                     Images = "off.jpg";
                     RelayOn = true;
                 }
             }

             loadSampleData();

         }

RelayControl.xaml如下:

 <?xml version="1.0" encoding="utf-8" ?>
 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
              x:Class="Socket.RelayControl"
              Title="Relay Control Page">

     <ContentPage.Content>
         <StackLayout Padding="10,0,0,10" Margin="2">
             <!--<SearchBar x:Name="MainSearchBar"                
             SearchButtonPressed="SearchBar_SearchButtonPressed"> 
             </SearchBar>-->
             <ListView x:Name="lstView" SelectionMode="None" 
              RowHeight="50" >
                 <ListView.ItemTemplate>
                     <DataTemplate>
                         <ViewCell >
                             <StackLayout Orientation="Vertical">
                                 <StackLayout Orientation="Horizontal">

                                <Label Text="{Binding Name,      
                                    Mode=OneWay}"
                                    x:Name="Received" 
                                    TextColor="#f35e20" 
                                    VerticalTextAlignment="Center"/>

                                <Image Source="{Binding ImageUrl, 
                                 Mode=OneWay}" Aspect="AspectFit"  
                                 HeightRequest="50" 
                                 WidthRequest="110" 
                                 HorizontalOptions="EndAndExpand" 
                                 VerticalOptions="Center">

                                    <Image.GestureRecognizers>
                                        <TapGestureRecognizer  
                                        CommandParameter="{Binding .}" 
                                        Tapped="ImageCell_Tapped" />
                                    </Image.GestureRecognizers>

                                </Image>
                                <!--LabelText="{Binding Name}" 
                                TextColor="DarkGoldenrod" ImageSource=" 
                                {Binding ImageUrl}" 
                               Tapped="ImageCell_Tapped">-->

                                 </StackLayout>
                             </StackLayout>
                         </ViewCell>
                     </DataTemplate>
                 </ListView.ItemTemplate>
             </ListView>

         </StackLayout>
     </ContentPage.Content>
 </ContentPage>

0 个答案:

没有答案