[英]Binding-Error with ComboBoxItem in DataGrid
我有一個帶有DataGrid
的UserControl
。 我將DataGrid
的列創建為DataGridTemplateColumn
。 DataGrid
看起來像:
<DataGrid Grid.Row="1" Style="{StaticResource DataGridStyle}" Margin="5"
ItemsSource="{Binding Storage.Items, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
MaxHeight="400" VerticalAlignment="Top">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Comment" Width="*" SortMemberPath="Comment">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Comment}" Margin="3,2" VerticalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
// several more column-definitions
<DataGridTemplateColumn Header="Actions" Width="90">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Margin="5" Content="Action..." Cursor="Hand" >
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<TextBlock TextDecorations="Underline" HorizontalAlignment="Center" Foreground="Blue">
<ContentPresenter/>
</TextBlock>
</ControlTemplate>
</Button.Template>
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<EventTrigger RoutedEvent="Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Edit"/>
<MenuItem Header="Delete" Command="{Binding DataContext.CommonCommand,
RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"
CommandParameter="{x:Static defs:CommonCommandTarget.Delete}"/>
<Separator/>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>+
</DataGrid.Columns>
</DataGrid>
我的問題是在最后一列中綁定了ContextMenu的Delete-Command。 顯示上下文菜單但單擊時沒有任何反應。
在輸出中我可以看到綁定錯誤:
System.Windows.Data錯誤:4:無法找到綁定源,引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.DataGrid',AncestorLevel ='1''。 BindingExpression:路徑= DataContext.CommonCommand; 的DataItem = NULL; target元素是'MenuItem'(Name =''); target屬性是'Command'(類型'ICommand')
在DataGrid
之外或直接在Template-Column中的Button
可以正常使用綁定。 所以Command是正確的。
什么Ancestor
或RelativeSource
或我必須提供什么,我將調用ViewModel中的命令?
您只能在Visual Tree的范圍內使用RelativeSource標記擴展。 DataGridTemplateColumn不是Visual Tree的一部分。 看看這個答案 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.