【问题标题】:Listview item tapped in xamarin.formslistview项在xamarin.forms中删除
【发布时间】:2016-06-29 05:22:18
【问题描述】:

我正在尝试在 Xamarin.Forms 和 XAML 中开发应用程序,并且我需要在点击 LV 时捕获事件。 我希望应用程序做的是当用户点击列表中的项目时更改单元格(或单元格内的 StackLayout)的颜色。 我正在尝试在列表视图上实现 OnItemTapped 属性,但是当我按下项目时没有任何反应。 我的代码很简单:

型号:具有 2 个属性、名称和颜色的产品。

public class Product: INotifyPropertyChanged
    {
        #region INotifyPropertyChanged implementation

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        public Product ()
        {
        }

        public string Name { get; set; }
        public bool Buy { get; set; }
        public  Color micolor { get; set; }

        //Método para actualizar los cambios
        protected virtual void OnPropertyChanged (string propertyName)
        {
            if (PropertyChanged == null)
                return;

            PropertyChanged (this, new PropertyChangedEventArgs (propertyName));
        }
    }

XAML:只有一个具有两个绑定的列表:标签中的名称和 SL 中的颜色

<?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="pruebalv.MyPage1">
    <ContentPage.Content>
     <ListView  x:Name="listView"
     ItemTapped="OmItemTapped"
     >

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout 
                        Orientation="Vertical"
                        BackgroundColor ="{Binding micolor}">
                                <Label Text="{Binding Name}"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ContentPage.Content>
</ContentPage>

在 .cs 代码后面:我创建了产品(这只是一个示例)并实现了点击的项目。当项目被点击时,我想改变被按下项目的颜色属性。

public void OmItemTapped (object o, ItemTappedEventArgs e)
        {
            var dataItem = e.Item as Product;
            dataItem.micolor  = Color.Green;
            dataItem.Name  = "Tapped!!";

        }

我在创建列表时得到的结果是,当我点击一个项目时没有任何反应。

我错过了什么吗?正如我在教程中所理解的那样,只有使用 ListView 的“itemtapped”roperty 和产品上的 InotifyProperty...,我才能看到结果。这是正确的吗? 谢谢!

【问题讨论】:

    标签: listview xamarin.forms uitapgesturerecognizer


    【解决方案1】:

    Xamarin.Forms MVVM 基础结构中的重要部分是您需要在更改属性值时显式调用 PropertyChanged。

    因此,您需要修改 ViewModel 代码,以便在属性更改时引发 PropertyChanged 事件。请参阅以下示例。

        private string name;
        public string Name 
        { 
            get { return name; }
            set 
            {
               name = value;
               OnPropertyChanged("Name");
            }
        }
    

    你必须对你的其他属性做同样的事情

    【讨论】:

    • 你说得对,我知道我错过了一些东西。谢谢!
    猜你喜欢
    • 2018-02-07
    • 1970-01-01
    • 2015-07-06
    • 2019-12-15
    • 2011-02-03
    • 2017-03-19
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    相关资源
    最近更新 更多