Skip to content

Instantly share code, notes, and snippets.

@weeksdev
Created January 28, 2016 14:21
Show Gist options
  • Save weeksdev/10db1364a6b6803490d9 to your computer and use it in GitHub Desktop.
Save weeksdev/10db1364a6b6803490d9 to your computer and use it in GitHub Desktop.
WPF MVVM Binding Example
class Base : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
this.VerifyPropertyName(propertyName);
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
public void VerifyPropertyName(string propertyName)
{
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
{
string msg = "Invalid property name: " + propertyName;
throw new Exception(msg);
}
}
}
class Main: Base
{
private string textfield = "Initial Value";
public string Textfield
{
get {
return textfield;
}
set {
textfield = value;
OnPropertyChanged("Textfield");
}
}
public void DoSomething()
{
}
}
<DockPanel LastChildFill="True">
<StackPanel DockPanel.Dock="Top" Height="50">
</StackPanel>
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">
<TextBox
Text="{Binding Path=Textfield, Mode=TwoWay}"
Width="200"
></TextBox>
<Button
Name="DoSomething"
Click="DoSomething_Click_1"
Content="Do Work"
Width="100"
HorizontalAlignment="Right"
Margin="20"
></Button>
</StackPanel>
<StackPanel>
</StackPanel>
</DockPanel>
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private viewmodel.Main vm;
public MainWindow()
{
InitializeComponent();
this.vm = new viewmodel.Main();
this.DataContext = vm;
}
private void DoSomething_Click_1(object sender, RoutedEventArgs e)
{
vm.DoSomething();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment