在 WPF 和 C# 上从其数据模板上的按钮删除 ListBoxItem

发布于 2024-10-12 09:23:52 字数 3517 浏览 7 评论 0原文

我一直在 WPF 上编写一个应用程序。它有一个绑定到 ObservableCollection<> 的 ListBox。自定义类的。使用具有 DELETE 按钮的 dataTemplate 显示数据,该按钮应该删除 ObservableCollection<> 的项目。

数据源集合的定义如下:

public class SellItem : INotifyPropertyChanged
{
    private string _name, _code, _details;
    
    public SellItem Self
    {
        get { return this; }
    }

    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Name"));
        }
    }
    public string Code
    {
        get
        {
            return _code;
        }
        set
        {
            _code = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Code"));
        }
    }
    public string Details
    {
        get
        {
            return _details;
        }
        set
        {
            _details = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Details"));
        }
    }
    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

public class ItemCollection : ObservableCollection<SellItem>
{
    static public ItemCollection theCollection = null;

    public ItemCollection()
    {
        theCollection = this;

    }
}

xaml 代码如下所示:

<Window x:Class="NALT_WPF.SaleWindow"
    ...
    xmlns:local="clr-namespace:NALT_WPF"
    Title="Test" Height="494" Width="838">
<Window.Resources>
    <ObjectDataProvider x:Key="theItemCollection" ObjectType="{x:Type local:ItemCollection}"/>
</Window.Resources>
<Window.CommandBindings>
    <!--Using command binding-->
    <CommandBinding Command="Delete" Executed="CommandBinding_Executed_RemoveAll" />
</Window.CommandBindings>
<Grid>
    <Grid.Resources>
        <DataTemplate x:Key="ProductListItemTemplate">
            <Grid>
                ...
                        <!-- This is the button on data template to remove the item from 'ItemCollection' -->
                        <Button Name="btRemoveAllItems" Content="X" 
                                Command="Delete" CommandParameter="{Binding Self}">
                        </Button>
                ...
            </Grid>
        </DataTemplate>
    </Grid.Resources>
    ...
    <ListBox Grid.Row="1" Margin="10" Name="lstProducts" 
                         ItemTemplate="{StaticResource ResourceKey=ProductListItemTemplate}"
                         ItemsSource="{Binding Source={StaticResource theItemCollection}}"
                         HorizontalContentAlignment="Stretch">
    </ListBox>
</Grid>

在主窗口 C# 代码上:

public partial class MainWindow : Window
{
    public SaleWindow()
    {
        InitializeComponent();
    }

    ...

    private void CommandBinding_Executed_RemoveAll(object sender, ExecutedRoutedEventArgs e)
    {
        // this is the code executed when DELETE button on data template is pressed.
        // I was thinking to remove the item here

        MessageBox.Show("Removing, proceed? ...");
         
        //...  ... 

        //...
        
    }
}

我该怎么做?从模板上的按钮所属的列表框中的集合中删除项目。该项目并不总是选定的项目。

I've been writing an application on WPF. It has a ListBox bound to a ObservableCollection<> of a custom class. The data is displayed using a dataTemplate which has a DELETE button that is supposed to remove the item of the ObservableCollection<>.

The data source collection is defined as shown:

public class SellItem : INotifyPropertyChanged
{
    private string _name, _code, _details;
    
    public SellItem Self
    {
        get { return this; }
    }

    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Name"));
        }
    }
    public string Code
    {
        get
        {
            return _code;
        }
        set
        {
            _code = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Code"));
        }
    }
    public string Details
    {
        get
        {
            return _details;
        }
        set
        {
            _details = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Details"));
        }
    }
    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

public class ItemCollection : ObservableCollection<SellItem>
{
    static public ItemCollection theCollection = null;

    public ItemCollection()
    {
        theCollection = this;

    }
}

The xaml code looks like this:

<Window x:Class="NALT_WPF.SaleWindow"
    ...
    xmlns:local="clr-namespace:NALT_WPF"
    Title="Test" Height="494" Width="838">
<Window.Resources>
    <ObjectDataProvider x:Key="theItemCollection" ObjectType="{x:Type local:ItemCollection}"/>
</Window.Resources>
<Window.CommandBindings>
    <!--Using command binding-->
    <CommandBinding Command="Delete" Executed="CommandBinding_Executed_RemoveAll" />
</Window.CommandBindings>
<Grid>
    <Grid.Resources>
        <DataTemplate x:Key="ProductListItemTemplate">
            <Grid>
                ...
                        <!-- This is the button on data template to remove the item from 'ItemCollection' -->
                        <Button Name="btRemoveAllItems" Content="X" 
                                Command="Delete" CommandParameter="{Binding Self}">
                        </Button>
                ...
            </Grid>
        </DataTemplate>
    </Grid.Resources>
    ...
    <ListBox Grid.Row="1" Margin="10" Name="lstProducts" 
                         ItemTemplate="{StaticResource ResourceKey=ProductListItemTemplate}"
                         ItemsSource="{Binding Source={StaticResource theItemCollection}}"
                         HorizontalContentAlignment="Stretch">
    </ListBox>
</Grid>

And on the main window C# code:

public partial class MainWindow : Window
{
    public SaleWindow()
    {
        InitializeComponent();
    }

    ...

    private void CommandBinding_Executed_RemoveAll(object sender, ExecutedRoutedEventArgs e)
    {
        // this is the code executed when DELETE button on data template is pressed.
        // I was thinking to remove the item here

        MessageBox.Show("Removing, proceed? ...");
         
        //...  ... 

        //...
        
    }
}

How can I do that? To remove the item from the collection on the listBox of which the button on the template belongs to. The item is not always the selected one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

渔村楼浪 2024-10-19 09:23:52

类似这样的:

private void CommandBinding_Executed_RemoveAll(object sender, ExecutedRoutedEventArgs e) 
{
    SellItem sellItem = (SellItem) e.Parameter;
    var itemsCollection = (ItemCollection)lstProducts.ItemsSource;
    itemsCollection.Remove(sellItem);
}

虽然,这似乎不对。您应该考虑以 MVVM 风格重写此代码。这样,您将拥有一个拥有产品列表的视图模型,并且该视图模型将定义一个删除命令,该命令将从集合中删除该项目。

还有一个提示。您无需定义 Self 属性即可绑定到它。您可以使用不带任何参数的绑定扩展:

<Button Name="btRemoveAllItems" Content="X" 
        Command="Delete" CommandParameter="{Binding}">

Something like this:

private void CommandBinding_Executed_RemoveAll(object sender, ExecutedRoutedEventArgs e) 
{
    SellItem sellItem = (SellItem) e.Parameter;
    var itemsCollection = (ItemCollection)lstProducts.ItemsSource;
    itemsCollection.Remove(sellItem);
}

Although, it doesn't seem right. You should consider rewriting this code in a MVVM style. This way you will have a view model that will own the list of products and that view model will define a Delete command that will delete the item from the collection.

And one more tip. You don't need to define a Self property to be able to bind to it. You can use the binding extension without any parameters:

<Button Name="btRemoveAllItems" Content="X" 
        Command="Delete" CommandParameter="{Binding}">
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文