如果我嘗試「var mainpage new Mainpage()」 我將運行主頁的構造函數,然後XAML對象中的所有字段將返回爲null。如何訪問Silverlight中的XAML對象,這些對象來自不同的類,但屬於同一名稱空間的一部分?如何從一個類訪問XAML對象以外的主?
讓我舉例說明。如果你看一下第一個答案,這裏是我我遇到
public class MyPage
{
MyPage()
{
// the constructor makes all the variables from the xaml null
}
public TextBox MyTextBox
{
get { return SomeTextBox; }
}
}
public class SomeOtherClass
{
private void SomeFunction()
{
var page = new MyPage(); // this makes the text empty
var sometext = page.MyTextBox.Text; // so sometext will be empty
}
}
所以,當我運行SomeFunction無論當程序第一次運行該用戶imputs變爲零。
我第一次嘗試的是看看是否創建了SomeClass時,將值放入該類中。
如果失敗了,我將嘗試MVVM。我已經看到了http://www.vimeo.com/8915487視頻和我得到的樣品MVVM代碼
這裏是型號:
namespace SimpleMVVM.Model
{
public class SimpleModel
{
// super easy version
//public string SomeSimpleValue { get; set; }
private string _SomeSimpleValue = string.Empty;
// actually do something version...
public string SomeSimpleValue
{
get
{
return "some value";
}
set
{
_SomeSimpleValue = value;
}
}
}
}
這裏的觀點:
和這裏是viewmodel.cs
using Simple;
using SimpleMVVM.Model;
namespace SimpleMVVM.ViewModel
{
public class SimpleViewModel : SimpleViewModelBase
{
private SimpleModel MyModel = new SimpleModel();
public string SomeSimpleValue
{
get { return MyModel.SomeSimpleValue; }
set
{
if (MyModel.SomeSimpleValue != value)
{
MyModel.SomeSimpleValue = value;
RaisePropertyChanged("SomeSimpleValue");
}
}
}
}
}
使用這個例子,我想知道它是否會像注入ViewModel一樣簡單,然後更改模型和視圖中的綁定。
是真的MVVM這容易嗎?
還有一個。它是視圖模型基類
using System.ComponentModel;
namespace Simple
{
public class SimpleViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string PropertyName)
{
var e = new PropertyChangedEventArgs(PropertyName);
PropertyChangedEventHandler changed = PropertyChanged;
if (changed != null) changed(this, e);
}
}
}
好了,現在最困難的部分。如果我創建一個新班級。我如何從viewmodel類獲取數據?
是的,MVVM就是這麼簡單(當你需要處理像按鈕點擊那樣的UI操作時,它變得更加複雜)。就我個人而言,我不同意你上面顯示的MVVM模式,但它現在會做。去找它,如果你還有問題,然後發佈一個新的問題。 – slugster 2011-06-15 08:07:45