【问题标题】:Binding to a property from a DataModel to its parent ViewModel?绑定到从 DataModel 到其父 ViewModel 的属性?
【发布时间】:2011-02-10 01:24:00
【问题描述】:

我正在使用 M-V-VM 模式。 我有一个 ViewModel 和一个 ObservableCollection 的 DataModel。 DataModel 列表是数据绑定到 DataGrid 的。

渲染网格时,我希望其中一个字段成为 ComboBox(假设是字符串名称列表)。

此字符串名称列表是适用于所有行(即 DataModels)的通用列表。

有没有办法将网格的字段级行属性绑定到父 ViewModel?

我想避免的一个可能的解决方案是: 在 DataModel 中有一个 get-property,它本质上返回 ViewModel 的属性(字符串名称列表)。

【问题讨论】:

    标签: silverlight data-binding datagrid mvvm


    【解决方案1】:

    您可以使用静态资源来做到这一点。 例如。在 xaml 中定义你的静态资源

    <UserControl.Resources>
       <mynamespace:MyViewModel x:Key="MyViewModel" />
    </UserControl.Resources>
    

    现在您可以在用户控件中引用此资源:

    <Controls::DataGrid DataContext="{StaticResource MyViewModel}" ItemSource="{Binding MyItems}" ...
      <Controls:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <ComboBox ItemsSource="{Binding MyItems, Source={StaticResource MyViewModel}" DisplayMemberPath="MyString" /> <!-- This does the job with the combo box and the strings -->
        </DataTemplate>
      </Controls:DataGridTemplateColumn.CellTemplate>
    </Controls:DataGrid>
    

    希望对你有帮助,

    BR,

    TJ

    【讨论】:

    • 所以我猜如果绑定属性在当前 DataContext 中找不到该属性,它不会遍历整个 DataContext 树(子模型到父视图模型)?让我试试这个吧!
    • 当我将静态资源引用添加到视图模型时,我的视图模型被创建了两次。问题是我在视图的构造函数中创建了视图模型(而不是在 xaml 中定义它)。
    • 是的,只要 被解析,对象就会被创建。你在这里有几个机会。例如,您将其设为 Singleton 并在启动 Application.Current.Resources.Add("MyViewModel", MyViewModel.Instance);) 时将其添加到 App 资源中,或者您通过应用程序资源引用创建的对象((MyViewModel)Application. Current.Resources["MyViewModel"];) 这对您有帮助吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    • 2011-02-01
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    相关资源
    最近更新 更多