如何从main以外的类访问XAML对象?

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

因此,当我运行SomeFunction时,程序首次运行时用户输入的任何内容都将变为null。

我首先要尝试的是查看是否在创建SomeClass时,将值放入该类中。

如果失败了,我将尝试MVVM。 我看过http://www.vimeo.com/8915487video,我得到了样本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类获取数据?

首先,让我把这个咆哮弄出来:你提出的建议非常糟糕。 它符合臭代码的定义。

如果你坚持这样做,那么“最好”的方法是在页面上声明一些返回实际UI元素的公共变量。

      public class MyPage { public TextBox MyTextBox { get { return SomeTextBox; } } } public class SomeOtherClass { private void SomeFunction() { var page = new MyPage(); page.MyTextBox.Text = "some text"; } } 

当然首选方法是使用类似MVVM模式的东西来实现从窗口到其视图模型的绑定,然后你可以从viewmodel中读取属性值,这样你就可以避免尝试从完全不同的方式触摸任何UI元素类。

另一种方法(不使用完整的MVVM路径)是将必要的值注入要实例化的控件/页面的构造函数中,然后可以将它们分配给相应的UI元素属性。 这仍然很臭,但比从外部直接访问UI元素更好。