如何在PropertyChangedCallback中将DependencyObject强制转换为FileInfo

时间:2018-04-19 14:03:34

标签: c# wpf dependencyobject

我有一个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
    }

错误是:

  

无法转换类型' System.Windows.DependencyObject'到' System.IO.FileInfo'

我想也许我错过了一些显而易见的东西(我可能是)但是Microsoftthis answer似乎同意我做的大致正确的事情。

1 个答案:

答案 0 :(得分:1)

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)
        {

        }
    }
}