DataContextProperty.OverrideMetadata to update DataContext : DataContextProperty « Windows Presentation Foundation « C# / C Sharp






DataContextProperty.OverrideMetadata to update DataContext

DataContextProperty.OverrideMetadata to update DataContext
  
<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window1" Height="100" Width="200">
  <StackPanel>
    <TextBox x:Name="tbxUserText" Text="Enter some text..."/>
    <Button Click="Button_Click" Content="Update DataContext"/>
  </StackPanel>
</Window>

//File:Window.xaml.cs
using System.Windows;
using System;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            DataContextProperty.OverrideMetadata(
                typeof(Window1), 
                new FrameworkPropertyMetadata(
                        100d, 
                        new PropertyChangedCallback(DataContext_PropertyChanged)));

        }

        private static void DataContext_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            string msg = string.Format("DataContext changed.{0}{0}Old Value: {1}{0}New Value: {2}",
                              Environment.NewLine,
                              e.OldValue.ToString(), 
                              e.NewValue.ToString());

            MessageBox.Show(msg, "changed");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DataContext = tbxUserText.Text;            
        }
    }
}

   
    
  








Related examples in the same category

1.Listen to DataContent changed eventListen to DataContent changed event