XAML将集合的子项绑定到ViewModel root的另一个集合

时间:2012-02-23 07:00:40

标签: xaml binding path

我很难将后续结构绑定到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的ComboBox,我想在SampleViewModel中使用Countries集合填充它。

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

ItemsSource应该是什么?如何在ItemsSource =“{Binding Child}”中返回root VM的属性?

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

1 个答案:

答案 0 :(得分: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}" />