これは簡単な例です。まず、ListBoxのソースクラス。 INotifyPropertyChangedインターフェイスと1つの文字列プロパティを実装する単純なクラスです。
public class MyClass : INotifyPropertyChanged
{
public MyClass(string myString)
{
MyString = myString;
}
private string m_myString;
public string MyString
{
get
{
return m_myString;
}
set
{
m_myString = value;
OnPropertyChanged("MyString");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
MainWindowにはObservableCollectionのMyClassがあります。 WindowのDataContextを自分自身に設定すると、ListBoxがDataContextを継承し、ItemsSourceをMyClassesにバインドできます。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MyClasses = new ObservableCollection<MyClass>();
MyClasses.Add(new MyClass("My String 1"));
MyClasses.Add(new MyClass("My String 2"));
MyClasses.Add(new MyClass("My String 3"));
this.DataContext = this;
}
public ObservableCollection<MyClass> MyClasses
{
get;
private set;
}
}
xamlには、MyClassesにバインドするListBoxがあります。 ItemTemplateは、ListBox内の各ListBoxItemに対して、各項目がMyClassのインスタンスにバインドされ、MyStringプロパティと「Remove Button」を提示します。各ListBoxItemのDataContextは、MyClassのインスタンスになります。
<ListBox ItemsSource="{Binding MyClasses}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding MyString}" Margin="6"/>
<Button Content="Remove"
Click="RemoveListBoxItem_Click"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
は最後に、我々はMainWindow.xaml.csにRemoveListBoxItem_ClickためEventHanlderの背後にあるコードを追加します。
private void RemoveListBoxItem_Click(object sender, RoutedEventArgs e)
{
// The clicked Button
Button button = sender as Button;
// The DataContext of the Button will be its instance of MyClass
MyClass selectedItem = button.DataContext as MyClass;
if (selectedItem != null)
{
// Remove the MyClass item from the collection
MyClasses.Remove(selectedItem);
}
}