Hallo zusammen,
heute möchte ich euch zeigen, wie ein einfaches Databinding mit automatischer Aktualsierung funktioniert.
WPF Binding mit INotifyPropertyChanged – Was benötigen wir!
1. Eine Klasse (Person) mit zunächst einer property
2. WPF mit zwei Textfeldern (Textbox)
FERTIG
1. Step: Wir erzeugen eine neue Klasse. Dazu geht in euer Projekt und erstellt eine Klasse Namens Person:
a.) Implementiert das Interface “INotifyPropertyChanged” => Ihr müsst danach den import “Imports System.ComponentModel” noch einbauen.
Imports System.ComponentModel Public Class Person Implements INotifyPropertyChanged Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged Public Sub New() Name = "Peter" End Sub Public Sub New(sName As String) Name = sName End Sub Public m_bauteiname As String Public Property Name() As String Get Return m_bauteiname End Get Set(ByVal value As String) m_bauteiname = value OnPropertyChanged("Name") End Set End Property Public Sub OnPropertyChanged(sMethodName As String) RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(sMethodName)) End Sub End Class
2. Jetzt benötigen wir unser WPF
<Window x:Class="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:DEIN_NAMESACE" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Window.Resources> <ResourceDictionary> <local:Person x:Key="person"/> </ResourceDictionary> </Window.Resources> <Grid> <StackPanel> <TextBox x:Name="txt_name" Height="50" Text="{Binding Source={StaticResource person}, Path=Name, Mode=TwoWay}" /> <TextBox x:Name="txt_name1" Height="50" Text="{Binding Source={StaticResource person}, Path=Name, Mode=TwoWay}" /> </StackPanel> </Grid> </Window>