2012-02-23 133 views
0

我有約束力的後續結構XAML瀏覽困難: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的實例設置爲視圖的DataContext的。我將集合Child綁定到GridView ItemsSource。在GridView中,我有一個ComboBox for Country,我想用SampleViewModel中的Countries集合填充它。

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

什麼應該是ItemsSource?我怎樣才能回到根目錄VM的屬性在一個ItemsSource =「{Binding Child}」?

或者我應該如何重構ViewModel才能達到上述目的?

回答

1

我不知道怎麼樣,如果這個工程與Telerik控制,但通常你聲明通過RelativeSource附加屬性的綁定:

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

另一種方法是在你的RadGridView設置一個名稱,並用其作爲元素名稱:

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

在我的示例的XAML中修復了我的愚蠢錯字之後,ElementName方法起作用。謝謝。 – Lepton 2012-02-23 08:44:17

相關問題