【问题标题】:Changing Entry Text change text in other Entry text in item of ListView更改条目文本更改 ListView 项目中其他条目文本中的文本
【发布时间】:2019-08-13 13:51:35
【问题描述】:

更新:

我有一个 ListView 可以通过按钮获取项目。 这些项目有这个模板:

<ListView x:Name="ListViewAlbaranFactura"
            Margin="10"
            CachingStrategy="RecycleElement"
            HasUnevenRows="True">

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Frame Margin="10" BackgroundColor="White">
                            <StackLayout>
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="*" />
                                        <RowDefinition Height="Auto" />
                                        <RowDefinition Height="*" />
                                        <RowDefinition Height="Auto" />
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto" />
                                        <ColumnDefinition Width="Auto" />
                                        <ColumnDefinition Width="40" />
                                    </Grid.ColumnDefinitions>


                                    <Button
                                        x:Name="BotonBorrarFacAlb"
                                        Grid.Row="0"
                                        Grid.Column="2"
                                        BackgroundColor="White"
                                        Clicked="BorrarItem"
                                        HorizontalOptions="End"
                                        Text="&#xf00d;">
                                        <Button.FontFamily>
                                            <OnPlatform
                                                x:TypeArguments="x:String"
                                                Android="fa-solid.ttf#Font Awesome 5 Free Solid"
                                                iOS="Font Awesome 5 Free" />
                                        </Button.FontFamily>
                                    </Button>
                                    <Label
                                        Grid.Row="0"
                                        Grid.Column="0"
                                        Text="Nro:" />
                                    <Label
                                        Grid.Row="1"
                                        Grid.RowSpan="2"
                                        Grid.Column="0"
                                        Text="Articulo:" />
                                    <Label
                                        Grid.Row="3"
                                        Grid.Column="0"
                                        Text="Relacion U/C:" />


                                    <Label
                                        Grid.Row="0"
                                        Grid.Column="1"
                                        LineBreakMode="TailTruncation"
                                        Text="{Binding IdFacAlb}" />
                                    <Label
                                        Grid.Row="1"
                                        Grid.RowSpan="2"
                                        Grid.Column="1"
                                        LineBreakMode="WordWrap"
                                        Text="{Binding ArtFacAlb}"
                                        VerticalTextAlignment="Start" />
                                    <Label
                                        Grid.Row="3"
                                        Grid.Column="1"
                                        LineBreakMode="TailTruncation"
                                        Text="{Binding UnidadesCajaFacAlb}" />


                                </Grid>
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="*" />
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto" />
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="Auto" />
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>
                                    <Label
                                        Grid.Row="0"
                                        Grid.Column="0"
                                        Text="{Binding Label1}" />
                                    <Label
                                        Grid.Row="0"
                                        Grid.Column="2"
                                        Text="{Binding Label2}" />

                                    <Entry
                                        x:Name="NameUnidadesFacAlb"
                                        Grid.Row="0"
                                        Grid.Column="1"
                                        Keyboard="Telephone"
                                        Text="{Binding UnidadesFacAlb}"
                                        />
                                    <Entry
                                        x:Name="NameCajasFacAlb"
                                        Grid.Row="0"
                                        Grid.Column="3"
                                        Keyboard="Telephone"
                                        Text="{Binding CajasFacAlb, StringFormat='{0:f2}'}"
                                         />

                                </Grid>
                                <Grid x:Name="gridTotal">
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="*" />
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*" />
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>
                                    <Label
                                        Grid.Row="0"
                                        Grid.Column="0"
                                        Text="Precio: " />
                                    <Label
                                        x:Name="TotalFacAlb"
                                        Grid.Row="0"
                                        Grid.Column="1"
                                        Text="{Binding TotalFacAlb, StringFormat='{0:F2} €'}" />

                                </Grid>

                                <Button
                                    BackgroundColor="Black"
                                    Clicked="btnGuardarAlbFac"
                                    HorizontalOptions="FillAndExpand"
                                    Text="Guardar"
                                    TextColor="White" />
                        </StackLayout>
                    </Frame>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

在我的 .CS 中,我将上下文绑定到:

public AlbaranFactura (Modelos.Lite.Cabecera cabecera, Modelos.Lite.Cliente cliente)
    {
        this.cabecera = cabecera;
        this.cliente = cliente;
        InitializeComponent ();
        this.albaranFactura = new Controladores.AlbaranFacturaController(cabecera, ListViewAlbaranFactura, cliente);
        this.BindingContext = albaranFactura;
    }

在AlbaranFacturaController:

public AlbaranFacturaController (Modelos.Lite.Cabecera cabecera, ListView ListViewAlbaranFactura, Modelos.Lite.Cliente cliente)
    {
        this.ListViewAlbaranFactura = ListViewAlbaranFactura;
        this.cliente = cliente;
        this.cabecera = cabecera;
        CargarAlbaranFactura();

        AddArticulo = new Command(abrir);
    }

CargarAlbaranFactura()load 数据在哪里:

public void CargarAlbaranFactura()
    {
        try
        {
            Utils.UIHandler.RunOnUI(() => {
                ListViewAlbaranFactura.BeginRefresh();
            });
            var NroCliente = cliente.CODIGO;
            var data = Conexiones.SQLiteHandler.GetSql(Connstring, "SELECT * FROM CabFacAlb;");
            Modelos.Lite.CabFacAlb cab = data.Select(q => SelectCabFacAlb(q)).Where(q => q.ClienteCFA == NroCliente).SingleOrDefault();
            var IdClienteTest = cab.NumCFA;
            var data2 = Conexiones.SQLiteHandler.GetSql(Connstring, "SELECT * FROM FacAlb;");
             List<Modelos.Lite.FacAlb> listadata2 = data2.Select(q => SelectFacAlb(q)).Where(q => q != null).ToList();

            var facalbList = new ObservableCollection<Modelos.Lite.FacAlb>();

            try
            {
                facalbList = new ObservableCollection<Modelos.Lite.FacAlb>(listadata2.Where(q => q != null && q.IdFacAlb == IdClienteTest ));
            }
            catch(Exception ex)
            {
                facalbList = null;
            }

            foreach(var item in facalbList)
            {
                var relacion = item.UnidadesCajaFacAlb;
                if(relacion == 0)
                {
                    item.Label1 = "Kg :";
                    item.Label2 = "Ud :";
                }
                else
                {
                    item.Label1 = "Ud :";
                    item.Label2 = "Cajas :";
                }
            }
            Utils.UIHandler.RunOnUI(() => {
                this.ListViewAlbaranFactura.ItemsSource = null;
                this.ListViewAlbaranFactura.ItemsSource = facalbList;
                ListViewAlbaranFactura.EndRefresh();
            });
        }
        catch (Exception ex)
        {
            Utils.UIHandler.ErrorDebug("Cargar Albaran/factura: Warning", ex.Message, Utils.UIHandler.MessageLevel.Warning);
        }

    }

我不明白如何将项目中的条目中的文本直接链接到其他条目文本。

我的物品是Modelos.Lite.FacAlb在哪里:

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

    public class FacAlb : INotifyPropertyChanged
{
    public long         IdContador { get; set; }
    public long         IdFacAlb { get; set; }
    public string       FechaFacAlb { get; set; }
    public string       TipoDocumento { get; set; }
    public string         ArtFacAlb { get; set; }
    public string unidadesFacAlb;
    public string cajasFacAlb;
    public string UnidadesFacAlb
    {
        get
        {
            return unidadesFacAlb;
        }
        set
        {
            try
            {
                if (value == unidadesFacAlb) return;
                unidadesFacAlb = value;
                if (UnidadesFacAlb != "")
                {
                    totalFacAlb = (PrecioFacAlb * double.Parse(UnidadesFacAlb))*((100-DtoFacAlb)/100);
                }
            }catch(Exception ex)
            {
                Console.WriteLine("Error " + ex.Message);
            }

            SetCajas();
        }

    }
    public string CajasFacAlb
    {
        get
        {
            return cajasFacAlb;
        }
        set
        {
            if (value == cajasFacAlb) return;
            cajasFacAlb = value;
            SetUnidades();
        }
    }
    public double?      UnidadesCajaFacAlb { get; set; }
    public double?      PrecioFacAlb { get; set; }
    public double?      DtoFacAlb { get; set; }
    public double?      totalFacAlb;
    public double?      TotalFacAlb
    {
        get
        {
            return totalFacAlb;
        }
        set
        {

            if (value == totalFacAlb) return;
            totalFacAlb = value;

        }
    }
    public string       Label1 { get; set; }
    public string       Label2 { get; set; }


    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

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

    void SetCajas()
    {
        if(UnidadesCajaFacAlb != 0 && UnidadesCajaFacAlb != null && UnidadesFacAlb != "")
        {
            double? valor = double.Parse(UnidadesFacAlb) / UnidadesCajaFacAlb;

            if(valor != null)
            {
                CajasFacAlb = valor.ToString();
            }
            else
            {
                CajasFacAlb = "";
            }

        }
        else
        {
            CajasFacAlb = "";
        }

    }
    void SetUnidades()
    {
        if(UnidadesCajaFacAlb != 0 && UnidadesCajaFacAlb != null && CajasFacAlb != "")
        {
            double? valor = double.Parse(CajasFacAlb) * UnidadesCajaFacAlb;
            if(valor != null)
            {
                UnidadesFacAlb = valor.ToString();
            }
            else
            {
                UnidadesFacAlb = "";
            }

        }
        else
        {
            UnidadesFacAlb = "";
        }
    }

    public FacAlb() { }
    public FacAlb(Dictionary<string, object> q)
    {

        this.IdContador = (long)q["IdContador"];
        this.IdFacAlb = (long)q["IdFacAlb"];
        this.FechaFacAlb = q["FechaFacAlb"] as string;
        this.TipoDocumento = (string)q["TipoDocumento"];
        this.ArtFacAlb = (string)q["ArtFacAlb"];
        this.PrecioFacAlb = double.Parse(q["PrecioFacAlb"].ToString());
        this.DtoFacAlb = (double?)q["DtoFacAlb"];
        this.UnidadesCajaFacAlb = q["UnidadesCajaFacAlb"] is DBNull ? 0 : (double?)q["UnidadesCajaFacAlb"];
        this.UnidadesFacAlb = q["UnidadesFacAlb"].ToString();
        this.CajasFacAlb = q["CajasFacAlb"].ToString();

    }

}

我如何构建控制 PropertyChanged 的​​ MVVM 函数?

【问题讨论】:

  • 这是完全错误的做法。 List 中的每一行都绑定到一个模型。所做的任何更改都应反映在该模型中。您不应该尝试直接在代码中与 UI 元素交互 - 相反,您应该使用模型中绑定到每个 UI 元素的值。
  • @Jason 那么,我如何在模型中进行交互,而不是直接使用 UI 元素进行更改?
  • 有大量文档和示例应用程序演示如何使用数据绑定
  • 我不明白您的物品的BindingContext 是什么...您能否更新您的帖子以向我们展示您的ListView 物品来源?作为一条全局规则,您不应该同时将 Text 绑定到上下文属性并使用 TextChanged,这违背了绑定的目的。
  • @Roubachof ItemSource 来自 ListView 是 {Modelos.Lite.FacAlb} 所以我知道如果我使用绑定来设置条目的文本,我不会使用 TextChanged,但是我如何为我的条目实现该操作模型。

标签: c# xamarin xamarin.forms


【解决方案1】:

如果在 FacAlb 中使用INotifyPropertyChanged,参数的设置/获取可以写成如下:

FacAlb:

public class FacAlb : INotifyPropertyChanged
{

private long idContador;
public long IdContador 
{
   set
   {
      if (idContador != value)
      {
         idContador = value;
         OnPropertyChanged("IdContador");
      }
    }
    get
    {
         return idContador;
    }
}

private long idFacAlb;
public long IdFacAlb 
{
   set
   {
      if (idFacAlb != value)
      {
         idFacAlb = value;
         OnPropertyChanged("IdFacAlb");
      }
    }
    get
    {
         return idFacAlb;
    }
}

privatestring fechaFacAlb;
public string FechaFacAlb 
{
   set
   {
      if (fechaFacAlb != value)
      {
         fechaFacAlb = value;
         OnPropertyChanged("FechaFacAlb");
      }
    }
    get
    {
         return fechaFacAlb;
    }
}

private string TipoDocumento;
public string tipoDocumento 
{
   set
   {
      if (tipoDocumento != value)
      {
         tipoDocumento = value;
         NotifyPropertyChanged("TipoDocumento");
      }
    }
    get
    {
         return tipoDocumento;
    }
}

private string artFacAlb;
public string ArtFacAlb 
{
   set
   {
      if (artFacAlb != value)
      {
         artFacAlb = value;
         NotifyPropertyChanged("ArtFacAlb");
      }
    }
    get
    {
         return artFacAlb;
    }
}
//... other code

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged([CallerMemberName] String propertyName = "")
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

//... other code

}

这里是a official document,还有关于using INotifyPropertyChanged in Xamarin.Forms的讨论。

【讨论】:

  • 谢谢,这很清楚,但还有一个问题,我已经更新了问题,如您所见。我想在 ListView 的前面看到应用的更改,所以,我想我也应该在我的 ModelView 中应用 PropertyChanged 吗?怎么样?
  • @ntzz 是的,listview的模型中需要自动更改的每个属性都应该应用propertyChanged。您只需在属性的set方法中添加OnPropertyChanged("PropertyName");。跨度>
  • @ntzz 如果listview中的item数量发生了变化,可以在数据更新后重新加载listview数据。
  • 谢谢!我将查看文档以了解所有内容。谢谢大家。还要感谢@Jason 和 Markus,他们也帮助了我 :)
  • @ntzz 太好了。这是一篇关于使用 RESTful Web 服务的文章。这种方式也可以更新列表视图。你也可以看看这个。如果有问题可以在这里更新,我会检查的。
猜你喜欢
  • 2012-07-01
  • 1970-01-01
  • 2020-07-10
  • 2012-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多