为WINRT实现MVVM示例

时间:2015-02-13 14:45:16

标签: c# mvvm windows-runtime

您好我正在尝试实施MVVM示例,但在我看来绑定并不起作用。我的问题不是没有问题。我的问题是为什么绑定是在xaml之间,viewmodel是不工作的。

有关代码的一些细节。

这是我的模特:

class Model : INotifyPropertyChanged {
    private String name;
    private String surname;
    public event PropertyChangedEventHandler PropertyChanged;

    public String Name {
        get {
        return name;
        }

        set {
        if (name != value) {
            name = value;
            NotifyPropertyChanged("Name");
        }
        }
    }

    // ...

    public void NotifyPropertyChanged(String propertyName) {
        PropertyChangedEventHandler handler = this.PropertyChanged;

        if (handler != null) {
        handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

查看模型

class ViewModel
{
    ObservableCollection<Model> Persons;
    private Model person;
    private String name;

    public ViewModel()
    {
        Persons = new ObservableCollection<Model>();
        Persons.Add(new Model
        {
            Name = "John"
        });
        Persons.Add(new Model
        {
            Name = "Nora"
        });
    }

    public ObservableCollection<Model> DataSource
    {
        get
        {
            if(Persons == null)
            {
                Persons = new ObservableCollection<Model>();
            }
            return Persons;
        }
    }

    public Model Person
    {
        get
        {
            return person;
        }

        set
        {
            if(person != value)
            {
                person = value;
                this.name = this.person.Name;
            }
        }
    }

    public String Name
    {
        get
        {
            return person.Name;
        }
    }

}

xaml文件

<ListView 
    ItemsSource="{Binding DataSource}" 
    SelectedItem="{Binding Person}" />
<TextBlock Text="{Binding Name}" />

主页代码隐藏

public MainPage()
{
    this.InitializeComponent();
    this.DataContext = new ViewModel();
}    

0 个答案:

没有答案