如果我尝试“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