WPF:如何在按下按钮时从列表中获取当前对象

busg9geu  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(128)

问题当我按下红色“X”时,我想从ObserableCollection中删除一篇文章。但我不知道如何获得当前Artcile。我有一个类Artcile。和保存不同文章的列表。
Xaml代码

<ItemsControl ItemsSource="{Binding CartArticles}">
 <ItemsControl.ItemTemplate>
     <DataTemplate>
         <Border BorderBrush="Black" BorderThickness="2" CornerRadius="30,30,30,30" Margin="0,15,0,30" MinWidth="100" MaxWidth="600" >
             <Grid Margin="0,0,0,10" Grid.Row="0">
                 <Grid.ColumnDefinitions>
                     <ColumnDefinition />
                     <ColumnDefinition />
                     <ColumnDefinition />
                 </Grid.ColumnDefinitions>

                 <Image Width="100" Height="70" Source="{Binding PathPic}" Margin="0,10,0,0"/>
                 <TextBlock FontWeight="Bold"  Grid.Column="1" FontSize="17" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Name}"/>

                 <StackPanel Grid.Column="2" HorizontalAlignment="Center" Orientation="Horizontal" VerticalAlignment="Center" >
                     <TextBlock FontWeight="Bold" FontSize="17" Foreground="DimGray" Text="{Binding Quantity}"/>
                     <TextBlock Text=" x " FontSize="16" Foreground="DimGray" />
                     <TextBlock FontWeight="Bold"  FontSize="17" Foreground="DimGray" Text="{Binding Price}" />
                     <TextBlock FontWeight="Bold"  FontSize="17" Foreground="DimGray" Text=" Euro" />
                 </StackPanel>

                 <StackPanel Grid.Column="2" HorizontalAlignment="Center" Orientation="Horizontal" VerticalAlignment="Bottom" >
                     <TextBlock FontWeight="Bold"  Grid.Column="2" FontSize="17" HorizontalAlignment="Center" VerticalAlignment="Bottom" Text="{Binding CompleteArticlePrice}"/>
                     <TextBlock FontWeight="Bold"  FontSize="17" Foreground="DimGray" Text=" Euro" />
                 </StackPanel>
                 <Button Name="DeleteCartArticle" Grid.Column="2" Width="20" Height="20" Margin="0,13,20,0" Content="X" FontSize="15" Foreground="Red" Background="Transparent" BorderThickness="0" HorizontalAlignment="Right" VerticalAlignment="Center" Click="DeleteCartArticle_Click"/>
             </Grid>
         </Border>
     </DataTemplate>
 </ItemsControl.ItemTemplate>

字符串

ObserableCollection


的数据

输出


n1bvdmb6

n1bvdmb61#

很高兴看到你从previous question继续前进:)
正如@Clemens所建议的,对于MVVM中的按钮,你也应该使用绑定和命令,它们将处理单击操作。但是如果你使用ItemsControl(而不是ListViewListBox,它们具有SelectedItem属性来简化我们的生活),按钮绑定有一个小技巧(在下面的XAML示例部分中描述)。
所以,首先你需要创建一个自定义类,它从System.Windows.Input命名空间实现ICommand接口。自定义命令类应该接受一些object作为参数,并且“对象”是来自ItemsControl的一个项目。所以,让我们称之为ParameterizedCommand

using System;
using System.Windows.Input;

namespace YourNamespace.Commands
{
    public sealed class ParameterizedCommand : ICommand
    {
        private readonly Action<object> _action;

        public ParameterizedCommand(Action<object> action) => _action = action;

        public bool CanExecute(object parameter) => true;
        public void Execute(object parameter) => _action(parameter);

        public event EventHandler CanExecuteChanged
        {
            add => CommandManager.RequerySuggested += value;
            remove => CommandManager.RequerySuggested -= value;
        }
    }
}

字符串
现在在你的ViewModel中(也就是前面的答案中的CartViewModel)添加一个命令,从CartArticles集合中删除CartArticle

public class CartViewModel
{
    // A collection, which stores articles in cart
    public ObservableCollection<CartArticle> CartArticles { get; } = new ObservableCollection<CartArticle>();

    private ICommand _removeCartArticle;
    public ICommand RemoveCartArticle => _removeCartArticle ?? (_removeCartArticle = new ParameterizedCommand(parameter =>
    {
        // Ensure that received parameter is CartArticle
        var cartArticle = parameter as CartArticle;
        if (cartArticle == null)
            return;

        CartArticles.Remove(cartArticle);
    }));

    // ...
}


最后,在视图中绑定按钮到该命令。要允许项目模板中的按钮“查找”ViewModel和存储的命令,您可以使用RelativeSource,它是父ItemsControl,作为CommandParameter,我们传递项目本身:

<ItemsControl ItemsSource="{Binding CartArticles}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>               
            <!-- ... -->                   
            <Button Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, Path=DataContext.RemoveCartArticle}"
                    CommandParameter="{Binding}"/>
            <!-- ... -->   
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>


现在,点击每个CartArticle中的“删除”按钮将从集合中删除该项目。只是不要忘记再次添加一些样式:
x1c 0d1x的数据

相关问题