如果我尝试“var mainpage new Mainpage()”
我将运行主页构造函数,然后 XAML 对象中的所有字段都将返回 null。如何在 silverlight 中访问来自不同类但属于同一命名空间的 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
}
}
因此,当程序首次运行时用户输入的任何内容在我运行某些函数时都会变为空。
我首先要尝试的是查看创建 SomeClass 时是否将值放入该类中。
如果失败,我将尝试 MVVM。我见过http://www.vimeo.com/8915487 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 真的这么简单吗?
还有一个。它是viewmodel基类
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 类获取数据?