我是WPF的新手,我正在尝试加载一个XAML窗口并在其构造函数中将变量传递给此XAML,因为我需要它从这个传递的变量中加载一些项目.
有人能指点我的方向吗?如何启动XAML窗口并为其提供变量?
在此先感谢.. Erika
尝试使用MVVM(Model-View-ViewModel)模式.
你需要型号:
class Person
{
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
View是您的窗口或UserControl.
ViewModel可以是这样的:
class PersonViewModel : INotifyPropertyChanged
{
private Person Model;
public ViewModel(Person model)
{
this.Model = model;
}
public string Name
{
get { return Model.Name; }
set
{
Model.Name = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var e = new PropertyChangedEventArgs(propertyName);
PropertyChangedEventHandler changed = PropertyChanged;
if (changed != null) changed(this, e);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您需要为窗口指定DataContext:
View.DataContext = new PersonViewModel(somePerson);
Run Code Online (Sandbox Code Playgroud)
然后在XAML中定义绑定:
<UserControl x:Class="SomeApp.View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<Grid>
<TextBlock Text="{Binding Name}" />
<Grid>
<UserControl>
Run Code Online (Sandbox Code Playgroud)
MVVM使代码非常优雅和简单.
您也可以尝试PRISM或Caliburn(http://caliburn.codeplex.com/)框架,但它们更复杂.
我的问题是我想访问 XAML 窗口之外的类,而不是通过 Binding 与相关代码进行通信。为此,我所需要做的就是创建一个静态类来保存我所需的值。很简单,但当时我却没有找到解决方案。这是解决问题的一种相当肮脏的方法,但它确实有效。
我要感谢两位帮助我理解 MVVM 架构的贡献者,因为我之前并没有真正理解它。
非常感谢您的及时回复,如果我的问题很容易被误解,我们深表歉意!有时我不太擅长传达我的想法。
| 归档时间: |
|
| 查看次数: |
9885 次 |
| 最近记录: |