Ich habe eine Anwendung auf WPF geschrieben. Es hat eine ListBox an eine ObservableCollection <> einer benutzerdefinierten Klasse gebunden. Die Daten werden mit einem dataTemplate angezeigt, das über eine DELETE-Schaltfläche verfügt, mit der das Objekt der ObservableCollection <> entfernt werden kann.Löschen eines ListBoxItem von einer Schaltfläche auf seiner Datenvorlage auf WPF und C#
ist die Datenquelle Sammlung wie dargestellt definiert:
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;
}
}
Der Code XAML sieht wie folgt aus:
<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>
Und auf dem Haupt # -Code Fenster 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? ...");
//... ...
//...
}
}
Wie kann ich das tun? Um das Element aus der Auflistung in der ListBox zu entfernen, zu der die Schaltfläche in der Vorlage gehört. Der Artikel ist nicht immer der ausgewählte.
Ich schätze jede Hilfe :)