【发布时间】:2018-11-27 13:17:35
【问题描述】:
我有一个绑定到ObservableCollection<ObservableCollection<BookModel>> 的ItemControl。最深的 ItemControl 中的每个项目都有一个按钮。我实现了一个每次单击按钮时都会触发的命令。
我的问题是我不知道应该将哪个参数传递给执行方法才能知道哪个 Item 触发了命令。意思是,如果按钮用作“添加图书”按钮,我想知道应该在哪里插入 BookModel 对象
<UserControl.Resources>
<DataTemplate x:Key="BooksViewTemplate">
<StackPanel>
<TextBlock>
<!-- This is where I bind data to the BookModel -->
</TextBlock>
<Button x:Name="AddNewBook"
Command="{Binding ElementName=LayoutRoot, Path = DataContext.AddBookCommand}"
<!-- CommandParameter= -->
/>
</StackPanel>
</<DataTemplate>
<DataTemplate x:Key="DataTemplate_level1">
<StackPanel>
<ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource BooksViewTemplate}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical">
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<ItemsControl ItemsSource="{Binding Books}" ItemTemplate="{DynamicResource DataTemplate_level1}" DataContext="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
public ICommand AddBookCommand
{
get
{
return _addBookCommnad ?? (_addBookCommand = new CmandHandler<object>((par) => AddBookAction(par), _canExecute));
}
}
public void AddBookAction(object obj)
{
//This is where I want to add a new BookModel to the
IObservableCollection<IObservableCollection<BookModel>> at the location
given by the pressed button
}
【问题讨论】:
-
您只是想找到插入新书的位置吗?或者这是一个层次结构,您需要知道要将图书添加到的父级?
-
你可以只传递“这个”吗? CommandParameter="{Binding . }" ?
-
@KevinCook 不确定我是否理解您的问题。我想知道将新书添加到哪一列以及将其插入到哪一行,这应该会影响
Iobservable<Iobservable<BookModel> -
只是想看看为什么你需要知道这一行。如果您需要以网格格式显示它,为什么不直接使用
> 然后使用 wrappanel。这就是为什么我要询问层次结构。 -
@RandRandom 当然你可以为命令参数指定一个绑定——我已经做了将近十年了
标签: c# wpf xaml datatemplate itemscontrol