using System; using System.Collections.Generic; 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 DependencyPropertySample { /// /// Interaction logic for MainWindow.xaml /// public partial class MainWindow : Window { // Dependency Property public static readonly DependencyProperty MyProperty = DependencyProperty.Register(nameof(MyFruit), typeof(string), typeof(MainWindow), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnMyPropertyChanged))); public MainWindow() { InitializeComponent(); } public string MyFruit { get { return (string)GetValue(MyProperty); } set { SetValue(MyProperty, value); } } public static void OnMyPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { MainWindow win = o as MainWindow; if (win == null) return; win.Title = (e.OldValue == null) ? "Not selected" : $"Old value is {e.OldValue.ToString()}"; win.txtFruit.Text = e.NewValue.ToString(); } private void cboMain_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBox cb = sender as ComboBox; if (cb == null) return; ComboBoxItem item = cb.SelectedItem as ComboBoxItem; if (item == null) return; MyFruit = item.Content.ToString(); } } }