我有绑定到列表框的项目,我已经实现了一个函数,可以在选择它们并且用户按 Delete 键时删除它们。 目前,删除功能直接访问源。 但是,除非用户先单击保存按钮,否则我不想修改源。
如何修改删除列表框项,以便在用户单击按钮之前不会更新我的源?
我绑定到的列表
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>
一种选择是创建收藏的副本并维护原始副本。例如,在初始化中的某个地方,调用:
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,只是这样做是为了在取消时强制刷新列表。