0

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.

Still.Tony
  • 1,437
  • 12
  • 35

1 Answers1

1

d refers to the control where the dependency property is defined, i.e. 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)
        {

        }
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Ok, yes that works (the `e.NewValue` version is what I tested just now) but do you know why conversion to FileInfo fails but other types apparently work fine? – Still.Tony Apr 19 '18 at 14:12
  • 1
    I am not sure I understand your question. Obviously you cannot cast anything that isn't a FileInfo to a FileInfo. And d is not a FileInfo in this case. – mm8 Apr 19 '18 at 14:15