【问题标题】:Why does not Xamarin bind property?为什么 Xamarin 不绑定属性?
【发布时间】:2019-11-18 09:48:00
【问题描述】:

我想在窗口关闭或应用程序崩溃时将数据保存到应用程序。

当用户写入条目时,数据会存储在属性中,但由于某种原因绑定不起作用。

为此,我参加了有关 Udemy 的课程。我认为这与引用 PCL 中的不同位置有关。

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TheIVInventory.ViewModels
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class AddItemPage : ContentPage
    {
        public AddItemPage()
        {

            InitializeComponent();

            BindingContext = Application.Current;


        }

        private void Button_Clicked(object sender, EventArgs e) //Item added click.
        {

        }
    }
}

Xaml:

<ContentPage 
     BackgroundColor="#104850"
    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="TheIVInventory.ViewModels.AddItemPage">

    <StackLayout VerticalOptions="Center" x:Name="formLayout" Margin="20">
        <Entry  PlaceholderColor="White" Keyboard="Chat" Margin="40" Placeholder="Item Name" TextColor="White" Text="{Binding ItemName}"></Entry>
        <Entry PlaceholderColor="White" Keyboard="Numeric" Margin="40" Placeholder="Item Price MIN (€)" TextColor="White"></Entry>
        <Entry PlaceholderColor="White" Keyboard="Numeric" Margin="40" Placeholder="Item Price MAX (€)" TextColor="White"></Entry>
        <Editor PlaceholderColor="White" Margin="40" VerticalOptions="FillAndExpand" Keyboard="Chat" Placeholder="Item Description" TextColor="White"></Editor>
        <Button Text="Save" BackgroundColor="#80EEFF"  Margin="10" Clicked="Button_Clicked" ></Button>
        <Image Source="konjakki.png" Scale="0.15" AnchorY="0" BackgroundColor="#104850" ></Image>
    </StackLayout>

</ContentPage>
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TheIVInventory
{
    public partial class App : Application
    {
        // Setting the item add members.
        private const string itemNameKey = "Name";
        private const string itemMinPrice = "0";

        public App()
        {
            InitializeComponent();

            MainPage = new NavigationPage(new MainPage())
            {
                BarBackgroundColor = Color.FromHex("#104850"),
                BarTextColor = Color.White


            }; // Making the navigation possible.
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }

        // Making the add item properties.

        public string ItemName
        {
            get
            {
                if (Properties.ContainsKey(itemNameKey))
                    return Properties[itemNameKey].ToString();

                return "";
            }
            set
            {
                Properties[ItemName] = value;
            }
        }

        public string ItemMinPrice
        {
            get
            {
                if (Properties.ContainsKey(itemMinPrice))
                    return Properties[itemMinPrice].ToString();

                return "";
            }
            set
            {
                Properties[itemMinPrice] = value;
            }
        }

    }
}

【问题讨论】:

  • 你为什么将Application.Current设置为你的BindingContext

标签: c# visual-studio xaml xamarin


【解决方案1】:

主要问题是您似乎没有设置 BindingContext 供 XAML 引用。

在我看来,你好像在尝试实现 MVVM 结构,但还没有完全理解它。

立即引起我注意的是:

  • 您的视图代码位于 ViewModel 命名空间而不是 View (这将在稍后证明令人困惑)。
  • 您的代码应位于主应用代码中的 ViewModel 类(将是您的 Views BindingContext)中。

我建议您创建一个 Views 命名空间并将您的 AddItemPage 代码移至其中; 创建一个 AddItemViewModel 并使用它来实现您的 ItemName 和 ItemMinPrice 属性。 不要在后面的代码中使用 button_clicked 事件,而是将 Button Command 绑定到 ViewModel 中的 ICommand 属性类型。然后让您的 ViewModel 实例化 ICommand 以使用内部方法来运行您的保存代码。

【讨论】:

    【解决方案2】:

    如果你想以 xamarin 形式实现 MVVM。你的绑定方式不对,你可以创建一个模型,将ItemMinPriceItemName放到这个模型中,如下代码。实现INotifyPropertyChanged接口,当数据发生变化时。

      class MyModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    
        string itemMinPrice;
        public string ItemMinPrice
        {
            set
            {
                if (itemMinPrice != value)
                {
                    itemMinPrice = value;
                    OnPropertyChanged("ItemMinPrice");
    
                }
            }
            get
            {
                return itemMinPrice;
            }
        }
    
    
    
        string itemName;
        public string ItemName
        {
            set
            {
                if (itemName != value)
                {
                    itemName = value;
                    OnPropertyChanged("ItemName");
    
                }
            }
            get
            {
                return itemName;
            }
        }
    
    }
    

    然后你可以改bindingContext,像这个代码BindingContext = new MyModel();

    我在MyModel 中添加了一个断点,在Entry 中给出一个itemName 你可以看到它是像下面的GIF 一样执行的。

    注意:如果要实现模型数据改变可以显示视图。您应该将Mode 更改为TwoWay,如下面的代码。

     <Entry  PlaceholderColor="White" Keyboard="Chat" Margin="40" 
       Placeholder="Item Name" TextColor="Black" Text="{Binding ItemName, 
       Mode=TwoWay}"></Entry>
    

    这里是关于 MVVM 的官方文章,你可以参考一下。 https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 2020-09-20
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 2018-05-06
      相关资源
      最近更新 更多