删除任务在上下文菜单下不起作用

本文关键字:不起作用 菜单 上下文 任务 删除 | 更新日期: 2023-09-27 18:30:50

我正在使用此示例开发Windows Phone应用程序:本地数据库示例

在该示例中,"删除任务"是使用图标实现的。我已经修改了删除任务 Context Menu.但是,它对我不起作用。

如果我按Delete,什么也没发生。

我不知道我犯了什么错误。

我修改的代码:

XAML 代码:

<TextBlock 
    Text="{Binding ItemName}" 
    FontWeight="Thin" FontSize="28" 
    Grid.Column="0" Grid.Row="0"
    VerticalAlignment="Top">
    <toolkit:ContextMenuService.ContextMenu>
    <toolkit:ContextMenu Name="ContextMenu">
    <toolkit:MenuItem Name="Delete"  Header="Delete" Click="deleteTaskButton_Click"/>
    </toolkit:ContextMenu>
    </toolkit:ContextMenuService.ContextMenu>
</TextBlock>

C# 代码:

private void deleteTaskButton_Click(object sender, RoutedEventArgs e)
    {
        // Cast the parameter as a button.
        var button = sender as TextBlock;
        if (button != null)
        {
            // Get a handle for the to-do item bound to the button.
            ToDoItem toDoForDelete = button.DataContext as ToDoItem;
            App.ViewModel.DeleteToDoItem(toDoForDelete);
            MessageBox.Show("Deleted Successfully");
        }
        // Put the focus back to the main page.
        this.Focus();
    }

该示例中的工作原始代码:

XAML 代码:

<TextBlock 
    Text="{Binding ItemName}" 
    FontSize="{StaticResource PhoneFontSizeLarge}" 
    Grid.Column="1" Grid.ColumnSpan="2" 
    VerticalAlignment="Top" Margin="-36, 12, 0, 0"/>
<Button                                
    Grid.Column="3"
    x:Name="deleteTaskButton"
    BorderThickness="0"
    Margin="0, -18, 0, 0"
    Click="deleteTaskButton_Click">
<Image 
    Source="/Images/appbar.delete.rest.png"
    Height="75"
    Width="75"/>
</Button>

C# 代码:

private void deleteTaskButton_Click(object sender, RoutedEventArgs e)
    {
        // Cast the parameter as a button.
        var button = sender as Button;
        if (button != null)
        {
            // Get a handle for the to-do item bound to the button.
            ToDoItem toDoForDelete = button.DataContext as ToDoItem;
            App.ViewModel.DeleteToDoItem(toDoForDelete);
            MessageBox.Show("Deleted Successfully");
        }
        // Put the focus back to the main page.
        this.Focus();
    }

删除任务在上下文菜单下不起作用

在您的情况下sender不是TextBlock,所以这一行:

var button = sender as TextBlock;

返回null

您可以将其转换为MenuItem .

using Microsoft.Phone.Controls;
....
private void deleteTaskButton_Click(object sender, RoutedEventArgs e)
{
    var item = sender as MenuItem;
    if (item!= null)
    {
        // Get a handle for the to-do item bound to the button.
        ToDoItem toDoForDelete = item .DataContext as ToDoItem;
        App.ViewModel.DeleteToDoItem(toDoForDelete);
        MessageBox.Show("Deleted Successfully");
    }
    // Put the focus back to the main page.
    this.Focus();
}