【问题标题】:Xamarin MvvM contentview bindingXamarin MvvM 内容视图绑定
【发布时间】:2015-01-23 04:22:20
【问题描述】:

我正在使用 Xaramin 开发应用程序。

在我的解决方案中,我创建了一个 ContentView.xaml,作为自定义 GUI 控件。

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:test2;assembly=test2"
    x:Class="test2.MyView">

    <ContentView.BindingContext>
        <local:MyViewModel MyValue="1"/>
    </ContentView.BindingContext>

    <StackLayout>
        <Label HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Text="{Binding MyValue}"/>
    </StackLayout>

</ContentView>

我已经为这个 ContentView 创建了一个 ViewModel 类:

using System;
using System.ComponentModel;
using Xamarin.Forms;

namespace test2
{
    public class MyViewModel : INotifyPropertyChanged
    {
        int myValue;

        public MyViewModel()
        {
            Device.StartTimer (TimeSpan.FromSeconds (1), () => {

                this.MyValue++;
                return true;
            });
        }

        public int MyValue
        {
            set
            {
                if (! myValue.Equals(value)) {

                    myValue = value;
                    OnPropertyChanged ("myValue");
                }
            }
            get
            { 
                return myValue;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) {

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

我还创建了一个 ContentPage.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"
    xmlns:local="clr-namespace:test2;assembly=test2"
    x:Class="test2.MyPage">

    <local:MyView />

</ContentPage>

我发现标签永远不会更新,为什么?

【问题讨论】:

  • ... Text="{Binding MyValue, Mode="TwoWay"}"/>

标签: c# xaml mvvm xamarin


【解决方案1】:

乍一看你应该替换

OnPropertyChanged ("myValue");

与

OnPropertyChanged ("MyValue");

因为属性名区分大小写

【讨论】:

  • 更新的答案是:OnPropertyChanged (nameof(MyValue));
猜你喜欢
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-29
  • 2021-06-27
  • 1970-01-01
  • 2021-11-05
相关资源
最近更新 更多