Das ObservableCollection-Binding

 

 

 

MainWindow.xaml:

<Window x:Class="BindingAnCollections.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingAnCollections"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" x:Name="fenster">
<Grid>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">

<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock Text="Name:" />
<TextBox Width="200" Text="{Binding PersonName, ElementName=fenster, Mode=OneWayToSource}"/>
<Button Content="in Liste eintragen" Click="Button_Click"/>
</StackPanel>

<ListBox Height="250" Margin="0, 10, 0, 0" ItemsSource="{Binding Persons, ElementName=fenster, Mode=OneWay}" DisplayMemberPath="Name"/>
</StackPanel>
</Grid>
</Window>


MainWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BindingAnCollections
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<Person> Persons { get; set; }
public string PersonName { get; set; }

public MainWindow()
{
Persons = new ObservableCollection<Person>();

InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
Person person = new Person();
person.Name = PersonName;

Persons.Add(person);
}
}
}


Person.cs:
namespace BindingAnCollections
{
public class Person
{
public string Name { get; internal set; }
}
}

Top