MVVM数据绑定到新对象实例

时间:2013-03-29 19:01:30

标签: silverlight windows-phone mvvm-light

我在Windows手机中使用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;

                                          }
                                     ));
        }
    }
}

View.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>

2 个答案:

答案 0 :(得分:0)

ViewModel未实现INotifyPropertyChanged接口。 MyModel及其所有属性也需要使用属性更改事件。

您显示在xaml中使用Model.Property1Model.Property1还需要引发属性更改事件。

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));
        }
    }      
}

答案 1 :(得分: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");
}
}