【发布时间】:2016-03-27 08:42:01
【问题描述】:
您好,我有一个列表框,每一行包含一个文本框和一个按钮;
使用单击按钮从列表框中删除该行;这适用于 mvvm 模式
我为此使用命令。
这是我的 xaml:
<DataTemplate x:Key="CategoryTemplate">
<Border Width="400" Margin="5" BorderThickness="1" BorderBrush="SteelBlue" CornerRadius="4">
<StackPanel Grid.Row="0" Orientation="Horizontal">
<TextBlock Width="300" Margin="5" Text="{Binding Path=Name}"></TextBlock>
<Button Name="btnDeleteCategory" Width="50" Margin="5"
Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource AncestorType=ListBox}}"
CommandParameter="{Binding}" Content="-" />
</StackPanel>
</Border>
</DataTemplate>
<ListBox Grid.Column="0" Grid.Row="0" Name="lstCategory"
ItemTemplate="{StaticResource CategoryTemplate}"
ItemsSource="{Binding Path=GetAllCategories}">
</ListBox>
在视图模型类中我有这个命令:
private ObjectButtonCommand<Category> _deleteCommand;
public ObjectButtonCommand<Category> DeleteCommand
{
get
{
return _deleteCommand
?? (_deleteCommand = new ObjectButtonCommand<Category>(
_category =>
{
GetAllCategories.Remove(_category);
}));
}
}
GetAllCategories 是 observecollection 属性;
这是我的 ObjectButtonCommand 代码:
public class ObjectButtonCommand<T> : ICommand
where T:class
{
private Action<T> WhatToExecute;
public ObjectButtonCommand(Action<T> What)
{
WhatToExecute = What;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
WhatToExecute((T)parameter);
}
}
现在一切正常,单击按钮时该行删除;
现在我希望当我选择一行列表框时重复此过程
我试试这个代码:
<ListBox Grid.Column="0" Grid.Row="0" Name="lstCategory" ItemTemplate="{StaticResource CategoryTemplate}" ItemsSource="{Binding Path=GetAllCategories}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding DataContext.DeleteCommand , RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding Path=SelectedItems,ElementName=lstCategory}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
但我在这段代码中收到此错误:WhatToExecute((T)parameter);
{“无法将'System.Windows.Controls.SelectedItemCollection'类型的对象转换为'Sepand.WPFProject.Model.Model.Category'类型。”}
我该怎么办?
【问题讨论】:
-
_deleteCommand应该是readonly。另外,下次请正确格式化您的问题。
标签: c# wpf mvvm binding selecteditem