【问题标题】:How to access UserControl's DataContext from another UserControl?如何从另一个 UserControl 访问 UserControl 的 DataContext?
【发布时间】:2015-09-19 07:59:21
【问题描述】:

我正在开发一个使用 Silverlight 5 编写的遗留应用程序,该应用程序包含许多反模式和不良做法。我负责使用 SingalR 添加实时交互(例如通知)。
顺便说一句,他们使用these WCF RIA 服务与身份验证进行交互。

他们有一个主页,这个页面是我获取用户通知并向登录用户显示它们的地方:

public partial class MainPage : UserControl
{
    public MainPage()
    {
       InitializeComponent();
       //...

    }
}

所以你可以看到,只要用户登录,我就没有设置 DataContext 属性,我需要在用户登录到应用程序后设置 MainPage 的 DataContext,所以我必须在 LoginOperation_Completed 里面的 @987654325 中这样做@页面:

public partial class LoginForm : StackPanel
{
   private LoginRegistrationWindow parentWindow;
   private LoginInfo loginInfo = new LoginInfo();
   public LoginForm()
   {
       InitializeComponent();
       //...
   }

   private void LoginOperation_Completed(LoginOperation loginOperation)
   {

    if (loginOperation.LoginSuccess)
    {
            // Here I need to access MainPages's DataContext property and set it with my ViewModel
    }
   }
}

现在我的问题是,如何在另一个类中设置 MainPage 的 DataContext 属性(在本例中为 LoginFrom)?

我还尝试为我的 MainPage 用户控件提供一个 ID 并像这样访问它:

mainPage.DataContext = new NotificationItemViewModel();

但是编译器给了我这个错误:

当前上下文中不存在名称“mainPage”

【问题讨论】:

  • 请添加您的 XAML
  • Here's MainPage 的 XAML。

标签: c# silverlight


【解决方案1】:

我终于想出了如何解决我的问题,有一个简单的方法可以实现这一点,我应该在类本身中创建MainPage类的静态实例:

public partial class MainPage : UserControl
{
    public static MainPage Instance { get; private set; }
    public MainPage()
    {
        InitializeComponent();
        Instance = this;
    }
}

现在我可以通过这种方式访问​​ MainPage 的 DataContext:

MainPage.Instance.DataContext = new NotificationItemViewModel();

【讨论】:

    【解决方案2】:

    您需要将MainPage UserControl 命名为您在LoginForm XAML 中粘贴的位置。不在MainPage的定义中。

    【讨论】:

    • 属性在 MainPage 里面,我为什么要命名 LoginForm?
    • 不,你不需要命名LoginForm。您需要在 LoginForm 的 XAML 中命名 MainPage 的实例。现在,您只需在MainPage 的描述中命名UserControl。如果您不明白,请向我展示您的 XAML LoginForm,我会帮助您。
    • Here's LoginForm 的 XAML。你能解释一下我该怎么做吗?
    • 抱歉,我没想到,但是您将控件放在哪里?好的,您描述了LoginForm 控件和MainPage 控件。但这并没有联系在一起。你有其他东西的容器吗?你把它放在哪里像实例?我只想告诉你,当你在MainPage.cs.xaml 中添加`Name="mainPage"` 时,意味着你可以在MainPage.cs.xamlMainPage.cs 中使用它。不在 LoginForm.cs 中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 2019-09-05
    相关资源
    最近更新 更多