仅当用户单击“保存”按钮时,才从ListBox中删除绑定项

时间:2015-03-10 15:37:05

标签: c# wpf data-binding updatesourcetrigger

我有一个项目绑定到列表框,我已经实现了一个功能,当他们被选中并且用户按下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>

1 个答案:

答案 0 :(得分: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,只是在Cancel上强制刷新列表。