0

我有绑定到列表框的项目,并且我已经实现了一个功能,可以在它们被选中并且用户按下 Delete 键时删除它们。目前,删除功能直接访问源。但是,除非用户先单击保存按钮,否则我不想修改源。

如何修改删除 ListBoxItems 以便在用户单击按钮之前不会更新我的源?

我绑定到的列表

public ObservableCollection<Process> Processes { get; set; }

删除功能

private void OnDeletePressed(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete)
    {
        foreach (Process item in ProcessListBox.SelectedItems.OfType<Process>().ToList())
        {
            SelectedRobot.Processes.Remove(item);
        }
    }
}

XAML

<ListBox x:Name="ProcessListBox" ItemsSource="{Binding Processes, UpdateSourceTrigger=Explicit}" KeyDown="OnDeletePressed">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Label Content="{Binding ProcessName}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
4

1 回答 1

0

一种选择是创建您的收藏的副本并保留原件。例如,在初始化的某个地方,调用:

    List<Process> pOriginalList = null;

    pOriginalList = Processes.ToList();



    private void OnDeletePressed(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Delete)
        {
            foreach (Process item in ProcessListBox.SelectedItems.OfType<Process>().ToList())
            {
                this.Processes.Remove(item);
            }
        }
    }

    private void OnSaveClick(object sender, RoutedEventArgs e)
    {
        // do nothing -- Processes already is set
    }

    private void OnCancelClick(object sender, RoutedEventArgs e)
    {
        Processes.Clear();
        Processes = new ObservableCollection<Process>(pOriginalList);
        this.DataContext = null;
        this.DataContext = this;
    }

XAML:

<Window x:Class="ListCopy.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <StackPanel>
            <Button Content="Save" Click="OnSaveClick" />
                <Button Content="Cancel" Click="OnCancelClick" />
            </StackPanel>
            <ListBox x:Name="ProcessListBox" ItemsSource="{Binding Processes, UpdateSourceTrigger=Explicit}" KeyDown="OnDeletePressed">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Label Content="{Binding ProcessName}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        </StackPanel>
    </Grid>
</Window>

这使得操作明确说明您何时需要对源进行实际更新。注意:不建议像这样设置 DataContext,只是为了在取消时强制刷新列表。

于 2015-03-10T17:50:20.030 回答