I'm trying to make a user control with a dependency property. I need to execute certain logic when the dependency property is changed from outside the usercontrol, but that logic shouldn't execute when the dependency property is changed from inside the user
control. I have this small sample. I only want to execute certain logic when the value is set from mainwindow and not when it is set by clicking the checkbox. I don't know if PropertyChangedCallback
is
the correct way, but this is what I have.
UserControl:
public partial class UserControl1 : UserControl { public int MyProperty { get { return (int)GetValue(MyPropertyProperty); } set { SetValue(MyPropertyProperty, value); } } public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(int), typeof(UserControl1), new PropertyMetadata(new PropertyChangedCallback(OnPropertyChanged))); private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { // Only process the 5, don't process the 6 } public UserControl1() { InitializeComponent(); } private void checkBox_Click(object sender, RoutedEventArgs e) { MyProperty = 6; } }
User control xaml:
<UserControl x:Class="WpfApplication4.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"><Grid><CheckBox x:Name="checkBox" Click="checkBox_Click"/></Grid></UserControl>
Mainwindow:
public partial class MainWindow : Window { public int MainWindowProperty { get; set; } public MainWindow() { InitializeComponent(); this.DataContext = this; MainWindowProperty = 5; } }
Mainwindow xaml:
<Window x:Class="WpfApplication4.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication4" Title="MainWindow" Height="350" Width="525"><Grid><local:UserControl1 MyProperty="{Binding MainWindowProperty}"/></Grid></Window>