如何在 PropertyChangedCallback 中将 DependencyObject 转换为 FileInfo

How to cast DependencyObject as FileInfo in PropertyChangedCallback

我有一个 FileInfo 类型的 DependencyProperty,在 PropertyChangedCallback 中,我无法将 DependencyObject 转换为 FileInfo 类型。

    public static readonly DependencyProperty TargetFileProperty =
        DependencyProperty.Register("TargetFile", typeof(System.IO.FileInfo), typeof(FileSelectGroup), new PropertyMetadata(propertyChangedCallback: new PropertyChangedCallback());

    private PropertyChangedCallback OnTargetFileChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var f = (System.IO.FileInfo)d; // THIS LINE GIVES ERROR BELOW
    }

错误是:

Cannot convert type 'System.Windows.DependencyObject' to 'System.IO.FileInfo'

我想也许我遗漏了一些明显的东西(我可能是),但 Microsoft and 似乎同意我做的大致是正确的。

d指的是定义依赖属性的控件,即FileSelectGroup.

您应该能够将 e.NewValue 转换为 System.IO.FileInfo 以获得依赖项的新值 属性:

private PropertyChangedCallback OnTargetFileChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var f = e.NewValue as System.IO.FileInfo;
    if (f != null)
    {
        //...
    }
}

或者,您可以将 d 转换为 FileSelectGroup 并访问控件的 TargetFile 属性:

private PropertyChangedCallback OnTargetFileChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var ctrl = d as FileSelectGroup;
    if (ctrl != null)
    {
        System.IO.FileInfo f = ctrl.TargetFile;
        if (f != null)
        {

        }
    }
}