单向依赖属性改变了通知

时间:2016-09-16 10:10:19

标签: c# wpf dependency-properties

我正在尝试使用依赖项属性创建用户控件。当从usercontrol外部更改依赖项属性时,我需要执行某些逻辑,但是当从用户控件内部更改依赖项属性时,不应执行该逻辑。我有这个小样本。我只想在从主窗口设置值时执行某些逻辑,而不是在通过单击复选框设置它时执行。我不知道device busy是否正确,但这就是我所拥有的。

用户控件:

PropertyChangedCallback

UserControl xaml:

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;
    }
}

主窗口:

<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 xaml:

public partial class MainWindow : Window
    {
        public int MainWindowProperty { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
            MainWindowProperty = 5;
        }
    }

1 个答案:

答案 0 :(得分:1)

private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (!disableProcessing)
    {
        // Only process the 5, don't process the 6
    }
}

bool disableProcessing = false;
private void checkBox_Click(object sender, RoutedEventArgs e)
{
    disableProcessing = true;
    MyProperty = 6;
    disableProcessing = false;
}