【发布时间】:2011-04-16 16:12:22
【问题描述】:
我有以下代码:
<Grid DataContext="{Binding ItemTypes}">
...
<TextBlock Text="Name:" />
<TextBox Grid.Column="2" Text="{Binding Name}" />
<TextBlock Grid.Row="1" Text="Description:" />
<TextBox Grid.Column="1" Grid.Row="1" Text="{Binding Description}" />
<TextBlock Grid.Row="2" Text="Manufacturer:" />
<ComboBox Grid.Column="1" Grid.Row="2" />
<TextBlock Grid.Row="3" Text="Short Name:" />
<TextBox Grid.Column="1" Grid.Row="3" Text="{Binding ShortName}" />
</Grid>
设置 Grid 的 DataContext 的 ItemTypes 来自包含另一个集合的 ViewModel。此网格内的制造商组合框需要填充其他集合。我试过这个:
ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType=Window, AncestorLevel=1}, Path=DataContext.companies}"
但它没有用。如何让组合框填充除 Grid 绑定的集合之外的其他集合?
ViewModel 代码:
public class ItemTypeViewModel
{
#region private fields
private ICollectionView collectionView;
private IItemTypeService itemTypeService;
#endregion
#region automatic properties
public ObservableCollection<ItemTypeViewModel> ItemTypes { get; private set; }
public IEnumerable<Company> companies { get; private set; }
#endregion properties
#region constructors
public ItemTypeAdminViewModel(IItemTypeService itemTypeService)
{
this.itemTypeService = itemTypeService;
Initialize();
collectionView = CollectionViewSource.GetDefaultView(ItemTypes);
}
#endregion
#region private methods
private void Initialize()
{
//TODO figure out if I should I wrap in Try/Catch here
ItemTypes = new ObservableCollection<ItemTypeViewModel>(itemTypeService.GetItemTypes());
companies = itemTypeService.GetCompanies();
}
#endregion
#region commands
public ICommand GoToFirst
{
get
{
return new RelayCommand(() => collectionView.MoveCurrentToFirst(),
() => collectionView.CurrentPosition >= 1);
}
}
public ICommand GoToLast
{
get
{
return new RelayCommand(() => collectionView.MoveCurrentToLast(),
() => collectionView.CurrentPosition < (ItemTypes.Count - 1));
}
}
public ICommand NextCommand
{
get
{
return new RelayCommand(() => collectionView.MoveCurrentToNext(),
() => collectionView.CurrentPosition < (ItemTypes.Count - 1));
}
}
public ICommand PreviousCommand
{
get
{
return new RelayCommand(() => collectionView.MoveCurrentToPrevious(),
() => collectionView.CurrentPosition >= 1);
}
}
#endregion
}
}
【问题讨论】: