0

我在 Windows Phone 中使用 MVVMlight。模型通过定位器通过 xaml 绑定。视图模型从 webrequest 加载模型的新实例,然后分配它。我不确定为什么视图没有被更新,是因为它分配了一个新实例吗?如果我更新模型的属性而不是分配新实例,它会在视图上更新。

分配模型的新实例时如何更新视图?

查看型号:

public class MyViewModel : ViewModelBase
{
    public MyModel Model { get; set; }

    public MyViewModel ()
    {
        if (IsInDesignMode)
        {
        }
        else
        {
            //async call
            api.GetModel(response =>
                                 Deployment.Current.Dispatcher.BeginInvoke
                                     (() =>
                                          {
                                              //this works.
                                              //Model.Property1 = "Some Text";
                                              //this doesn't work
                                              Model = response.Data;

                                          }
                                     ));
        }
    }
}

查看.xaml

<UserControl x:Class="Grik.WindowsPhone.CardDetailsView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    DataContext="{Binding MyModel, Source={StaticResource Locator}}" >

    <Grid x:Name="LayoutRoot" >
        <TextBlock Text="{Binding Model.Property1}" />

    </Grid>
</UserControl>
4

2 回答 2

0

ViewModel 没有实现INotifyPropertyChanged接口。MyModel以及它的所有属性也需要使用属性更改事件。

你展示你Model.Property1在xaml中使用,Model.Property1还需要引发property changed事件。

public class MyModel : INotifyPropertyChanged
{
    private string _Property1 = "";

     public string Property1
    {
        get { return this._Property1; }

        set
        {
            if (value != this._Property1)
            {
                this._Property1 = value;
                NotifyPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }      
}
于 2013-03-29T20:48:00.070 回答
0

我想在 View Model Locator 类中查看您的代码

在 MyViewModel 类中,您可能需要重写此属性

public MyModel Model { get; set; }

private MyModel _model; 
public MyModel Model { 
get{return this._model;}
set{
    this._model = value;
    this.NotifyPropertyChanged("Model");
}
}
于 2013-04-01T20:17:17.503 回答