简体   繁体   English

如何在PropertyChangedCallback中将DependencyObject转换为FileInfo

[英]How to cast DependencyObject as FileInfo in PropertyChangedCallback

I have a FileInfo type DependencyProperty and in the PropertyChangedCallback , I can't cast the DependencyObject to FileInfo type. 我有一个FileInfo类型的DependencyProperty,并且在PropertyChangedCallback ,我无法将DependencyObject FileInfoFileInfo类型。

    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
    }

Error is: 错误是:

Cannot convert type 'System.Windows.DependencyObject' to 'System.IO.FileInfo' 无法将类型“ System.Windows.DependencyObject”转换为“ System.IO.FileInfo”

I thought maybe I was missing something obvious (I probably am) but Microsoft and this answer seem to agree I'm doing roughly the right thing. 我以为也许我遗漏了一些明显的东西(我可能是),但是微软这个答案似乎都同意我在做正确的事。

d refers to the control where the dependency property is defined, ie the FileSelectGroup . d指定义了依赖项属性的控件,即FileSelectGroup

You should be able to cast e.NewValue to a System.IO.FileInfo to get the new value of the dependency property: 您应该能够将e.NewValue转换为System.IO.FileInfo以获得依赖项属性的新值:

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

Alternatively you could cast d to FileSelectGroup and access the TargetFile property of the control: 或者,您可以将d FileSelectGroupFileSelectGroup并访问控件的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)
        {

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM