我有以下代码:
<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。此Grid中的制造商Combobox需要填充其他集合。我试过这个:
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
}
}
答案 0 :(得分:0)
假设您的视图模型设置为Window.DataContext
,而您的其他集合MyOtherCollection
是视图模型中的属性。将您的ComboBox
更改为以下内容:
<ComboBox Grid.Column="1" Grid.Row="2"
ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}, Path=DataContext.MyOtherCollection}" />
答案 1 :(得分:0)
我想说的是,不要在DataContext
上设置Grid
。而是单独绑定每个项目。除非您提供进一步的信息,特别是您的VM,否则很难提供进一步的建议。
答案 2 :(得分:0)
在构造函数中为视图的datacontext分配了什么。如果通过构造函数注入将视图的datacontext指定为viewmodel,则应该能够直接绑定为ItemsSource="{Binding companies}"