【发布时间】:2022-11-24 05:05:08
【问题描述】:
我有一个 **ListView **,它绑定到一个 ObservableCollection
我已经将 DataTemplate 添加到 ListView 以使用 TextBox 将项目绑定到 Rename selectedItem 使用从 ContextMenu 重命名:
看法
<ListView DockPanel.Dock="Left"
Background="MidnightBlue"
Width="140"
SelectedItem="{Binding SelectedNotebook, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding Notebooks}"
x:Name="notebooksList"
SelectionChanged="notebooksList_SelectionChanged"
SelectionMode="Single">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<uc:DisplayNotebook Notebook="{Binding}">
<uc:DisplayNotebook.ContextMenu>
<ContextMenu>
<MenuItem Header="Rename"
Command="{Binding Source={StaticResource vm}, Path=EditCommand}"
CommandParameter="{Binding SelectedNotebook}"/>
<MenuItem Header="Delete"
Command="{Binding Source={StaticResource vm}, Path=DeleteNotebookCommand}"
CommandParameter="{Binding SelectedNotebook}"/>
</ContextMenu>
</uc:DisplayNotebook.ContextMenu>
</uc:DisplayNotebook>
<TextBox Text="{Binding Name, Mode=TwoWay}"
Visibility="{Binding Source={StaticResource vm}, Path=IsVisible}"
x:Name="notebookTextBox">
<i:Interaction.Triggers>
<i:EventTrigger EventName="LostFocus">
<i:InvokeCommandAction Command="{Binding Source={StaticResource vm}, Path=EndEditingCommand}"
CommandParameter="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
视图模型
public async void StopEditingNotebook(Notebook notebook)
{
IsVisible = Visibility.Collapsed;
await DatabaseHelper.Update(notebook);
GetNotebooks();
}
public async void StopEditingNote (Note note)
{
IsVisible = Visibility.Collapsed;
await DatabaseHelper.Update(note);
GetNotes();
}
命令
public class EndEditingCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public NotesVM ViewModel { get; set; }
public EndEditingCommand(NotesVM vm)
{
ViewModel = vm;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
Notebook notebook = parameter as Notebook;
if (notebook != null)
ViewModel.StopEditingNotebook(notebook);
}
}
public class EditCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public NotesVM ViewModel { get; set; }
public EditCommand(NotesVM vm)
{
ViewModel = vm;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
ViewModel.StartEditing();
}
}
我想Rename一次只弹出一个文本框,而不是同时弹出所有文本框(这是由于 DataTemplate 中的绑定文本框而导致的)。
我想知道如何找到一个 ID of selectedItem 然后以某种方式只显示这个特定的文本框。
你对这件事有什么想法吗? 提前感谢您的帮助
【问题讨论】:
标签: wpf listview data-binding datatemplate listviewitem