我在这个项目中关注MVVM .
我有WPF数据网格,
ItemsSource (ItemsSource="{Binding Documents}")
绑定到 ObservableCollection<Document>
,
SelectedItem (SelectedItem="{Binding CurrentDocument, Mode=TwoWay}")
绑定到 WorkQueueDocument
,
我还使用了交互触发来捕获鼠标的双击 - 以便在新窗口中加载所选文档 .
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding ShowViewerCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
我已将datagrid的列定义/绑定到WorkQueueDocument类的相应属性 .
<DataGrid.Columns>
<DataGridTextColumn Width="Auto"
MinWidth="100"
Header="Name"
Binding="{Binding Name}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Margin" Value="2,0,0,0" />
<Setter Property="ToolTip" Value="{Binding Name}" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<!-- Many Other Columns Here... -->
</DataGrid.Columns>
<DataGrid.ColumnHeaderStyle>
<!-- I have various designer style's properties defined here -->
</DataGrid.ColumnHeaderStyle>
我应该在用户选择网格中的行(文档)时加载文档 - 因为CurrentDocument属性定义如下:
public WorkQueueDocument CurrentDocument
{
get
{
return this.currentDocument;
}
set
{
if (this.currentDocument != value)
{
this.currentDocument = value;
this.OnPropertyChanged("CurrentDocument");
this.IsDocumentSelected = true;
// If we are in progress already, don't do anything
if (!IsLoading && this.currentDocument != null)
{
IsLoading = true;
LoadDocumentBackgroundWorker();// loading documenting async
}
if (this.currentDocument == null)
{
this.IsDocumentSelected = false;
}
}
}
}
现在,问题是 - 我想在此数据网格中添加一个删除按钮列,这样当用户按下删除按钮时 - 文档会被直接删除而不加载文档 . 我添加了以下xaml到 <DataGrid.Columns>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Name="DeleteBatch"
Content="Delete"
Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.DeleteCommand}"
CommandParameter="Delete"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
这个 DeleteCommand
没有被解雇 . 我试图找出原因并发现我有
第一个命令在datagrid中,用于在选择行时加载文档
ItemsSource="{Binding Documents}"
第二个命令是在上面的datagrid的coluumn中的删除按钮
<Button Name="Delete"
Content="Delete"
Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.DeleteCommand}"
CommandParameter="Delete">
,我一次只能访问一个命令 . 当我点击按钮 - 行('显然') gets selected and executed associated binding for ' SelectedItem '但没有跟进调用
DeleteCommand (理想情况下应该这样) . 但是,如果我删除这个' SelectedItem '属性 - deleteCommand被触发(但后来我没有得到选定的行) .
Also (while debugging i noticed) the DeleteCommand 在第二次按(点击)时执行(现在已经选择了行) **
我用谷歌搜索 - 并找到了一些可能的解决方案,如优先绑定和隧道,但无法实现 . 请指导我完成这个 .
我得到了link,但不确定这是否是唯一的方法 .
P.S:1 . 我正在使用WPF,.Net 4.0和MVVM
- 请不要建议第三方解决方案 . [除非唯一的选择]
1 回答
CommandParameter="{Binding}"
yourDocumentObservableCollection.Remove(CommandParameter)
这样您就不需要关心文档是否关注 .