Wpf UserControl中用作ListBox.ItemTemplate的命令绑定
我有一个Wpf UserControl中用作ListBox.ItemTemplate的命令绑定,wpf,data-binding,command,commandbinding,Wpf,Data Binding,Command,Commandbinding,我有一个列表框,其中用户控件作为数据模板。此UserControl具有一个按钮,用于从列表中删除该项 <ListBox x:Name="FileList" ItemsSource="{Binding Files}" > <ListBox.ItemTemplate> <DataTemplate> <Views:FileItem/> </DataTemplate> </List
列表框
,其中用户控件
作为数据模板
。此UserControl
具有一个按钮
,用于从列表中删除该项
<ListBox x:Name="FileList" ItemsSource="{Binding Files}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Views:FileItem/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
以下是简化的UserControl
:
<UserControl x:Class="Views.FileItem">
<Canvas x:Name="LayoutRoot">
<TextBlock x:Name="FileName" Text="{Binding FileName}" />
<Button Content="Remove"/>
</Canvas>
</UserControl>
当用户单击Remove
按钮时,应将此项目从observedcollection
中删除
问题是,每个ListBoxItem
的DataContext
与保存ObservableCollection
的ViewModel不同
我不知道如何将
Remove
按钮绑定到“父”视图模型中的ICommand
。任何帮助都将不胜感激。非常感谢 我会将按钮绑定到UserControl的ViewModel中的ICommand,然后使用松散耦合的消息传递将消息发送到父ViewModel(在大多数Mvvm框架中可用,如)
让父VM注册“remove me”消息,并相应地更新ObservableCollection
希望这有帮助:)谢谢。这帮了大忙。我担心在开发过程中会遇到更多的场景,而中介模式解决了所有这些场景。
<UserControl x:Class="Views.FileItem">
<Canvas x:Name="LayoutRoot">
<TextBlock x:Name="FileName" Text="{Binding FileName}" />
<Button Content="Remove"/>
</Canvas>
</UserControl>