c# - 从 DependencyProperty PropertyChangedCallback 获取父对象

标签 c# .net wpf dependency-properties

我想在每次更改属性时执行一些代码。以下在一定程度上起作用:

public partial class CustomControl : UserControl
{
        public bool myInstanceVariable = true;
        public static readonly DependencyProperty UserSatisfiedProperty =
            DependencyProperty.Register("UserSatisfied", typeof(bool?),
            typeof(WeeklyReportPlant), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnUserSatisfiedChanged)));


        private static void OnUserSatisfiedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Console.Write("Works!");
        }
}

当 UserSatisfiedProperty 的值改变时,这会打印“Works”。问题是我需要访问调用 OnUserSatisfiedChanged 的​​ CustomControl 实例以获取 myInstanceVariable 的值。我该怎么做?

最佳答案

实例通过 DependencyObject d 参数传递。您可以将其转换为您的 WeeklyReportPlant 类型:

public partial class WeeklyReportPlant : UserControl
{
    public static readonly DependencyProperty UserSatisfiedProperty =
        DependencyProperty.Register(
            "UserSatisfied", typeof(bool?), typeof(WeeklyReportPlant),
            new FrameworkPropertyMetadata(new PropertyChangedCallback(OnUserSatisfiedChanged)));

    private static void OnUserSatisfiedChanged(
        DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var instance = d as WeeklyReportPlant;
        ...
    }
}

关于c# - 从 DependencyProperty PropertyChangedCallback 获取父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15173867/

相关文章:

c# - 获取 WPF 数据网格上下文菜单单击行

c# - LINQ:转换集合中的项目

.net - 有一个 sln 文件,可以列出该 sln 下所有项目的所有文件吗?

C# Julian 日期解析器

c# - 如何将 RibbonControlLibrary 功能区事件机制与 TabControl 结合使用?

c# - 两个属性 - 第二个属性类型取决于第一个属性

c# - 我如何记录一个 c# dll

c# - 在 C# 中使用 LINQ 计算百分位

c# - 多个 Linq 函数作为参数

javascript - http post 方法被视为 http get 方法