【问题标题】:Referencing a UIElement in a ViewModel from XAML从 XAML 引用 ViewModel 中的 UIElement
【发布时间】:2011-02-16 21:55:38
【问题描述】:

我对使用 WPF 和 MVVM 架构比较陌生。我有一个关于从 XAML 窗口的 DataContext 引用 UIelements 的问题。

我有使用以下语法绑定到 Views DataContext 的菜单项:

<MenuItem Header="About" Command="{Binding AboutCommand}" />

我想使用类似的范例将项目添加到网格中。现在我正在使用一个类 WorkflowDesigner。我可以在我的 ViewModel 中使用以下代码将它添加到我的网格中:

grid.AddChildren(wd.View)

其中视图的类型为UIElement

我宁愿在我的 XAML 文件中添加对它的引用,而不在我的代码隐藏中添加任何内容,这样我就可以将 XAML 主要用作皮肤。是否可以使用仅从 XAML 文件的数据上下文中获取其 UIElement 的标签?

【问题讨论】:

    标签: wpf xaml binding uielement


    【解决方案1】:

    这是可能的,但让您的 ViewModel 为您的视图提供控件并不符合 MVVM 的精神。理想情况下,您的 ViewModel 应该完全不依赖 System.Windows.Controls。

    如果必须,那么您可以使用ContentControl

    <ContentControl Content={Binding wd.View} />
    

    为了处理这个问题,我将创建一个 ViewLocator 类并将它的一个实例放入您的资源字典中。然后使用这个:

    <ContentControl Content={Binding Source={StaticResource ViewLocator}, Path=WorkflowDesigner} />
    

    【讨论】:

      【解决方案2】:

      我不确定我是否完全理解您的问题,但如果您希望通过 ViewModel 在视图中呈现一个类,您可以使用 ItemsControl 来显示不同的类,使用 DataTemplate

      假设你有课User

      public class User
      {
          public string Id { get; set;}
          public string Name { get; set;}
      }
      
      
      public class UserViewModel
      {
          private ObservableCollectionaUser<User> _users = new......
          public ObservableCollection<User> Users
          {
              get
              {
                  return _users;
              }
          }
      }
      

      在 UserView 中,您可以拥有

      <ItemsControl ItemsSource="{Binding Users}">
          <ItemsControl.Resources>
              <DataTemplate>
                  <StackPanel Orientation="Horizontal">
                     <TextBlock Text="{Binding Id}" />
                     <TextBlock Text="{Binding Name}" />
                  </StackPanel>
              </DataTemplate>
          </ItemsControl.Resources>
      </ItemsControl>
      

      这样,用户将使用上面声明的模板显示在视图中。这样您就不必在 ViewModel 中使用 UIElements。

      ItemsControl 可以引用网格项,并使用 SharedGridScope 将项显示在网格中(如果我没记错的话)。

      【讨论】:

        猜你喜欢
        • 2020-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-09
        • 1970-01-01
        相关资源
        最近更新 更多