簡體   English   中英

WPF ContextMenu忽略CanExecute

[英]WPF ContextMenu ignores CanExecute

我在該視圖后面有一個帶元素的DataGrid和一個ViewModel。 ViewModel有一個RelayCommand,它實現CanExecuteChanged。 DataGridRow有一個樣式,該樣式具有ContextMenu,其MenuItems綁定到RelayCommand並將該項目作為參數傳遞。 這是XAML:

<ContextMenu  x:Key="CommentMenu" DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}">       
    <MenuItem Header="Bind to Project" Command="{Binding BindToProjectCommand}" 
              CommandParameter="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}}"/>        

</ContextMenu>
<Style x:Key="DefaultRowStyle" TargetType="{x:Type DataGridRow}">
    <Setter Property="ContextMenu" Value="{StaticResource CommentMenu}" />
</Style>
...
<DataGrid ItemsSource="{Binding Comments}"
                  RowStyle="{StaticResource DefaultRowStyle}"
                  IsReadOnly="True"
                  CanUserAddRows="False">

這是ViewModel:

public MyViewModel()
{
   BindToProjectCommand = new RelayCommand<Comment>(BindToProject, CanBindToProject);
}

public bool CanBindToProject(Comment comment)
{
    var answer = comment != null && comment.ProjectId == null;
    return answer;
}

在運行時調用CanExecuteChanged,將正確的注釋作為參數傳遞,返回true,但菜單項仍處於禁用狀態。 輸出窗口沒有綁定錯誤,因此綁定絕對正確,我可以看到正確的實例。 所以問題是:1.為什么CanExecute的結果被忽略? 2.如何使其工作?

謝謝您的意見。

因此,我發現CommandParameter的綁定始終綁定到列表中的最后一個注釋。 最簡單的解決方法是將SelectedItem綁定到ViewModel中的屬性,並如下更改命令和CanBindToProject方法:

            <DataGrid ItemsSource="{Binding Comments}"              
                  IsReadOnly="True"
                  CanUserAddRows="False"
                  RowStyle="{StaticResource DefaultRowStyle}"
                  SelectedItem="{Binding SelectedComment}"
                  SelectionMode="Single"/>

public Comment SelectedComment
public RelayCommand BindToProjectCommand(BindToProject, CanBindToProject)

public bool CanBindToProject()
{
     return SelectedComment != null && SelectedComment.ProjectId == null;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM