[英]WPF Prism listbox button
我将项目从数据库拉到一个包含几列的列表框中。 我想为从数据库中提取的每个项目添加一个删除按钮,但是我似乎无法转发该项目的ID,它始终显示为0。
<ListBox ItemsSource="{Binding LbPlugins}" HorizontalContentAlignment="Stretch" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<CheckBox Grid.Column="0" Content="{Binding Name}" IsChecked="{Binding IsActive}"/>
<Label Grid.Column="1" Content="{Binding ClassName}"/>
<Button Grid.Column="2" Content="E" Command="{Binding btnEditPluginCommand}"/>
<Button Grid.Column="3" Content="D" Command="{Binding Path=DataContext.btnDeletePluginCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter="{Binding PluginId}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
在ViewModel中:
private int pluginId;
public int PluginId
{
get { return pluginId; }
set { SetProperty(ref pluginId, value); }
}
public DelegateCommand btnDeletePluginCommand { get; set; }
...
在构造函数中
btnDeletePluginCommand = new DelegateCommand(DeletePlugin);
...
private void DeletePlugin()
{
var result = MessageBox.Show("Are you sure you want to delete this plugin?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
MessageBox.Show("YAY, ID=" + pluginId);
}
}
使用Prism时,应使用DelegateCommand
,这是Prism的ICommand
实现。
为了使这项工作有效,您需要使用一个对象或可为null的类型作为通用CommandDelegate
参数。 如果不这样做,则在运行时将收到InvalidCastException
。
像这样声明您的命令:
public ICommand btnDeletePluginCommand { get; set; }
在viewmodel的构造函数上初始化它:
btnDeletePluginCommand = new DelegateCommand<int?>(DeletePlugin);
并重构您的方法:
private void DeletePlugin(int? pluginId)
{
if (pluginId == null) return;
var result = MessageBox.Show("Are you sure you want to delete this plugin?", "", MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
MessageBox.Show("YAY, ID=" + pluginId);
}
当您确实将命令绑定到ListBox时,pluginId参数永远不会为null,但您应该始终进行验证。 也许您将此ViewModel与其他UI组件一起使用?
顺便说一句,您不应该在视图模型中使用MessageBox
。 我想这是概念的证明或:)。 对于MVVM,您应该注入DialogService或使用InteractionRequests显示来自视图模型的通知。
希望这可以帮助!
由于您已经从xaml传递了参数,因此可以使用:
btnDeletePluginCommand = new Microsoft.Practices.Prism.Commands.DelegateCommand<int>(DeletePlugin);
然后,您的DeletePlugin应该具有这样的一个参数:
private void DeletePlugin(int pluginId)
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.