【问题标题】:XAML binding collection's child item to ViewModel root's another collectionXAML 将集合的子项绑定到 ViewModel 根的另一个集合
【发布时间】:2012-02-23 07:00:40
【问题描述】:

我很难将以下结构绑定到 XAML 视图:

public class SampleViewModel : ViewModelBase
{
   public ObservableCollection<ChildViewModel> Child { get; set; }
   ...
   public ObservableCollection<Country> Countries { get; set; }
   ...
}
public class ChildViewModel : ViewModelBase
{
   private int _CountryId;
   public int CountryId
   {
      get { return _CountryId; }
      set
      {
         _CountryId = value;
         OnPropertyChanged("CountryId");
      }
   }
   ...
}
// Country structure is not shown, just an int and string for CountryID 
// and Name in this case

SampleViewModel 的实例被设置为 View 的 DataContext。我将集合 Child 绑定到 GridView ItemsSource。在 GridView 中,我有一个 Country 组合框,我想用 SampleViewModel 中的 Country 集合填充它。

<Telerik:RadGridView ItemsSource="{ Binding Child }" ...>
   <Telerik:RadGridView.Columns>
      <Telerik:GridViewComboBoxColumn DataMemberBinding="{Binding CountryId}"
                                      SelectedValueMemberPath="Id"
                                      DisplayMemberPath="Name"
                                      ItemsSource="{Binding ????}" />
      ...
   ...
...

ItemsSource 应该是什么?如何返回 ItemsSource="{ Binding Child }" 中的根 VM 属性?

或者我应该如何重构 ViewModel 以实现上述目标?

【问题讨论】:

    标签: xaml binding path


    【解决方案1】:

    我不确定这是否适用于 Telerik 控件,但通常您通过 RelativeSource 附加属性声明绑定:

    {Binding Path=DataContext.Countries, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Telerik:RadGridView}}}
    

    另一种方法是在 RadGridView 上设置一个名称并将其用作 ElementName:

    <Telerik:RadGridView ItemsSource="{ Binding Child }" x:Name="gridView">
    ...
          <Telerik:GridViewComboBoxColumn DataMemberBinding="{Binding CountryId}"
                                          SelectedValueMemberPath="Id"
                                          DisplayMemberPath="Name"
                                          ItemsSource="{Binding DataContext.Countries, ElementName=gridView}" />
    

    【讨论】:

    • 在我的示例 XAML 中修正了我愚蠢的错字之后,ElementName 方式起作用了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 2016-10-11
    • 2018-10-13
    • 1970-01-01
    • 2012-12-10
    • 2010-11-19
    • 1970-01-01
    相关资源
    最近更新 更多