我有一个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'
我想也许我错过了一些显而易见的东西(我可能是)但是Microsoft和this answer似乎同意我做的大致正确的事情。
答案 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)
{
}
}
}