我对 WPF 还很陌生,我正在尝试加载一个 XAML 窗口并在其构造函数中将一个变量传递给此 XAML,因为我需要它从这个传递的变量中加载一些项目。
有人能给我指出如何解决这个问题的方向吗?
如何启动 XAML 窗口并给它一个变量?
提前致谢..
埃里卡
尝试使用 MVVM(模型-视图-视图模型)模式。
您需要型号:
class Person
{
public string Name { get; set; }
}
视图是您的窗口或用户控件。
ViewModel 可以是这样的:
class PersonViewModel : INotifyPropertyChanged
{
private Person Model;
public PersonViewModel(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);
}
}
然后您需要为您的窗口指定 DataContext:
View.DataContext = new PersonViewModel(somePerson);
然后在 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>
MVVM 使代码变得非常优雅和简单。
你也可以尝试PRISM或卡利本(http://caliburn.codeplex.com/)框架,但它们更复杂。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)