【发布时间】:2012-04-06 16:09:08
【问题描述】:
背景:
我有一个包含用户控件的主窗口的 WPF 应用程序。我想将一个值从主窗口传递给用户控件。
在主窗口的构造函数中我有代码:
public MainWindow()
{
InitializeComponent();
_vm = new MainWindowViewModel();
this.DataContext = _vm;
ucControl = new UserControl1("NameSet");
}
(ucControl 是我的用户控件)
用户控件有两个构造函数:
public UserControl1()
{
InitializeComponent();
this.ID = ID.GetNewID;
}
public UserControl1(string name)
{
InitializeComponent();
_vm = new UCViewModel(name);
this.DataContext = _vm;
this.ID = ID.GetNewID;
}
问题是:虽然调用了第二个构造函数(带参数),但它并没有加载到主窗口中。我检查了用户控件的加载事件中的 ID (this.ID),我看到在默认构造函数中设置的 ID 并且它的 DataContext 为空。由于这个原因,我没有在我的用户控件中获得“名称”字符串。
有什么帮助吗?由于我使用的是 MVVM 模式,因此我不想公开用户控件(视图)中的属性,以便为此从主窗口设置。
【问题讨论】:
-
你从那里加载了这个用户控件.. 显示更多代码
-
用户控件在主窗口的 xaml 中。
-
我猜这个问题类似于stackoverflow.com/questions/4802278/…。这会有所帮助。
-
是的,您应该尝试在用户控件中创建依赖属性并使用它而不是 ctor 中的参数
-
但是属性“name”在 ViewModel 中,是不是在 View(用户控件)中声明了一些针对 MVVM 模式的业务属性?
标签: wpf mvvm user-controls