For fast and dirty Windows in WPF, I prefer to bind the DataContext window to the window itself; all of this can be done in XAML.
Window1.xaml
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding RelativeSource={RelativeSource self}}" Title="Window1" Height="300" Width="300"> <StackPanel> <TextBlock Text="{Binding Path=MyProperty1}" /> <TextBlock Text="{Binding Path=MyProperty2}" /> <Button Content="Set Property Values" Click="Button_Click" /> </StackPanel> </Window>
Window1.xaml.cs
public partial class Window1 : Window { public static readonly DependencyProperty MyProperty2Property = DependencyProperty.Register("MyProperty2", typeof(string), typeof(Window1), new UIPropertyMetadata(string.Empty)); public static readonly DependencyProperty MyProperty1Property = DependencyProperty.Register("MyProperty1", typeof(string), typeof(Window1), new UIPropertyMetadata(string.Empty)); public Window1() { InitializeComponent(); } public string MyProperty1 { get { return (string)GetValue(MyProperty1Property); } set { SetValue(MyProperty1Property, value); } } public string MyProperty2 { get { return (string)GetValue(MyProperty2Property); } set { SetValue(MyProperty2Property, value); } } private void Button_Click(object sender, RoutedEventArgs e) {
In the above example, notice the binding used in the DataContext the window, it says: "Set your data context for yourself." Two text blocks are attached to MyProperty1 and MyProperty2 , the event handler for the button will set these values, which automatically apply to the Text property of two text blocks, since the properties are dependency properties.
Phil Price Mar 21 '09 at 21:36 2009-03-21 21:36
source share