更改ViewModel属性,在另一个类中不更新UI

时间:2018-05-17 12:01:45

标签: c# xamarin mvvm xamarin.forms

我在一个更复杂的应用程序中使用了这个问题,所以我构建了一个简单的应用程序来测试它。但首先是代码,这是一个简单的应用程序的奇怪布局,但请记住,这模仿我的其他应用程序。

注意,Baseviewmodel继承自basemodel。

的MainPage

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="TestINotify.MainPage"
             xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:TestINotify">
  <ContentPage.BindingContext>
    <local:MainPageViewModel />
  </ContentPage.BindingContext>

  <StackLayout>
    <!--  Place new controls here  -->
    <Label HorizontalOptions="Center"
           Text="Welcome to Xamarin.Forms!"
           VerticalOptions="CenterAndExpand" />
    <Label HorizontalOptions="Center"
           Text="{Binding LabelTextProperty}"
           VerticalOptions="CenterAndExpand" />
    <Button Command="{Binding ChangeTextCommand}" Text="Change Label Text" />

  </StackLayout>

</ContentPage>

MainPageViewModel

public class MainPageViewModel : BaseViewModel
{
    public ICommand ChangeTextCommand { private set; get; }

    private string _labelText = "Default text" ;

    public string LabelTextProperty
    {
        get
        {
            return _labelText;

        }
        set
        {
            _labelText = value;
            OnPropertyChanged();
        }
    }

    public MainPageViewModel()
    {
        ChangeTextCommand = new Command(execute: () =>
        {
            var handler = new ChangeTextClass();
            handler.ChangeTexts();

        });

    }

}

ChangeTextClass

    public class ChangeTextClass
    {
        public MainPageViewModel mpvm = new MainPageViewModel();
        public void ChangeTexts()
        {
            mpvm.LabelTextProperty = "The Text Was Changed ?";

        }
    }

BaseModel

public abstract class BaseModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

当我通过

在视图模型中指定标签的文本值时
    ChangeTextCommand = new Command(execute: () =>
    {
       LabelTextProperty = "Local works";

    });

它运行正常,但是,这可能与我在类中创建视图模型的新实例有关吗?

0 个答案:

没有答案