0

我正在使用此示例开发 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();
    }
4

1 回答 1

0

在你的情况下sender不是 a 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();
}
于 2013-09-11T08:11:41.883 回答