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

时间:2013-09-11 07:55:14

标签: c# windows-phone-7 windows-phone-8 windows-phone

我正在使用此示例开发Windows Phone应用:Local Database Sample

在该示例中,使用图标实现了删除任务。我已经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();
    }

1 个答案:

答案 0 :(得分:0)

在你的情况下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();
}