简体   繁体   中英

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.

    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'

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 .

You should be able to cast e.NewValue to a System.IO.FileInfo to get the new value of the dependency property:

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:

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

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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