【问题标题】:how to prevent a user control to get the datacontext, when it's hidden?如何防止用户控件在隐藏时获取数据上下文?
【发布时间】:2011-02-22 17:59:01
【问题描述】:

我有一个 wpf-mvvm 应用程序。

我有一个基类 - baseViewModel...

还有另外两个继承这个基类的类

 class aVM : baseViewModel
    {
       public string a {get;set;}
    }

    class bVM : baseViewModel
    {
      public string b {get;set;}
    }

还有另一个类——作为主视图模型——绑定到主视图。

   Class MainVM
   {
     public baseViewModel CurrentViewSource  {get;set;}
   }

还在 XAML 文件(视图)中 - 我有两个用户控件。但是这两者的数据上下文是相同的公共属性 - CurrentViewSource - 这是类型 - baseViewModel。

<---MainView start DataContext="MainVM" ----->

<---user control 1 satrt----->
  <--DataContext = "CurrentViewSource " -->
  // Here CurrentViewSource  is of type aVM
<---user control 1 end ----->

<---user control 2 start----->
  <-- DataContext = "CurrentViewSource " -->
  // Here CurrentViewSource  is of type bVM   
<---user control 2 end----->

<---MainView end----->

我需要一次显示一个用户控件..并隐藏另一个。

由于两个用户控件 (UC) 使用相同的数据上下文变量“CurrentViewSource”,

如果 UC1 可见(UC2 隐藏)- CurrentViewSource 将是 aVM 类型...和 ​​UC2(即使隐藏)..将其用作数据上下文 ..并且无法看到字符串 b。

...Visual Studio 显示一些绑定问题。请帮帮我

【问题讨论】:

    标签: wpf mvvm


    【解决方案1】:

    ContentPresenter 与隐式Data Templates 结合使用。

    因此,在您的主视图中,在您将显示一个或另一个用户控件的位置,使用 ContentPresenter 并将其 Content 属性绑定到 CurrentViewSource

    <ContentPresenter Content="{Binding CurrentViewSource}"/>
    

    现在,对于每个支持的视图模型类型,在主视图的资源中定义一个 DataTemplate

    <Window ...>
       <Window.Resources>
           <DataTemplate DataType="{x:Type my:aVM}">
              <my:aUserControl/>
           </DataTemplate>
    
           <DataTemplate DataType="{x:Type my:bVM}">
              <my:bUserControl/>
           </DataTemplate>
       </Window.Resources>
    ...
       <ContentPresenter Content="{Binding CurrentViewSource}"/>
    ...
    </Window>
    

    这样,无论何时更改CurrentViewSource,都会应用相应的DataTemplate

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-06
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      相关资源
      最近更新 更多