【发布时间】:2018-02-04 02:33:55
【问题描述】:
假设我有一个具有不同属性的ViewModel 类,例如:
//MainVm will inherit ViewModel that contains IPropertyChanged implementation
public class MainVM : ViewModel
{
publi bool Foo { get; set; }
}
我以这种方式在主controller 上设置了这个类:
MainController mc;
public MaiWindow()
{
mc = new MainController();
DataContext = mc;
InitializeComponent();
}
MainController 有这个实现:
public class MainController : MainVM
{
some methods
}
所以每次我需要访问每个 UserControls 上的 MainController 的属性时,我需要这样做:Application.Current.MainWindow.mc.Foo
这一点也不优雅。
不调用上面的代码行是否可以访问特定ViewModel的属性?
谢谢。
更新
要为这个问题添加更多详细信息和说明:所以在我的 UserControl 中,我需要访问属于MainVM 的Foo 属性。我谈到了UserControl xaml 代码(不是 UserControl 的控制器),这是一个示例:
public partial class ControlName : UserControl
{
public ControlName()
{
InitializeComponent();
}
public btnAdd_Click(object sender, RoutedEventArgs e)
{
//Suppose that I need to access to the property Foo of MainVM here
//I need to access to MainWindow instance like this:
Application.Current.MainWindow.mc.Foo
//isn't possible instead access to the property directly inherit the class, like:
MainVm.Foo
}
}
【问题讨论】:
-
你能说得更具体些吗?您需要在应用程序的哪个部分使用“Application.Current.MainWindow.mc.Foo”?如果您的代码在控制器中,则不需要 Application.Current,而且我很难看到您需要在外部应用程序中访问控制器的位置。如果您可以在问题的最后一部分添加更多代码。
-
@PhillipH 确保检查更新
-
嗨。我猜你不理解 MVVM 背后的想法。请先检查msdn.microsoft.com/en-us/library/hh848246.aspx,然后尝试使用框架或工具包,如mvvmlight.net/creating
-
@Marco 我已经实现了 MVVM 逻辑,我只是问如何在不通过 MainWindow 实例的情况下访问特定控制器的属性
-
嗯,你正在使用 btnAdd_Click 告诉我它仍然不是 MVVM。无论如何,在 ControlName 中,您可以将 DataContext 强制转换回 MainController 或 MainVM ......这很糟糕,但它会起作用。我仍然建议阅读我发送的文档,您发布的代码不是 MVVM
标签: c# wpf mvvm user-controls