我正在使用依赖项属性创建文件选择器UserControl
来存储表示打开文件对话框的初始目录的字符串:
public static readonly DependencyProperty DefaultFolderProperty =
DependencyProperty.Register("DefaultFolder", typeof(string), typeof(FileSelector), new PropertyMetadata(Path.GetDirectoryName(Directory.GetCurrentDirectory())));
public string DefaultFolder
{
get { return (string)this.GetValue(DefaultFolderProperty); }
set { this.SetValue(DefaultFolderProperty, value); }
}
此属性绑定到Textbox
中的UserControl
,因此我可以手动编写目录地址:
<TextBox x:Name="SelectedFolder" Style="{DynamicResource BaseTextBoxStyle}" FontSize="8" Grid.Column="3" Grid.ColumnSpan="2" Text="{Binding DataContext.DefaultFolder, ElementName=F_Selector, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
此属性也是通过浏览器选择对话框设置的:
private void SelectFolderDialog()
{
WPFFolderBrowserDialog vfb = new WPFFolderBrowserDialog();
vfb.InitialDirectory = @"C:";
if (vfb.ShowDialog() ?? false)
{
this.Dispatcher.Invoke(DispatcherPriority.Send, new Action(delegate
{
DefaultFolder = vfb.FileName;
}));
}
}
现在,当我使用此属性设置选择文件对话框的InitialDirectory
时,这样:
private void AddFileDialog()
{
System.Windows.Forms.OpenFileDialog vfb = new System.Windows.Forms.OpenFileDialog();
vfb.Multiselect = true;
vfb.Title = "pouet";
vfb.RestoreDirectory = true;
vfb.InitialDirectory = DefaultFolder;
System.Windows.Forms.DialogResult dr = vfb.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
this.Dispatcher.Invoke(DispatcherPriority.Send, new Action(delegate
{
for (var i = 0; i < vfb.FileNames.Length; i++)
{
FileDisplay.Add(vfb.FileNames[i]);
}
}));
}
}
无论我在InitialDirectory
属性中使用什么,如果它不是一个硬编码目录,它就不起作用并使我的应用程序崩溃抛出异常:
An unhandled exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll Additional information:
The calling thread cannot access this object because a different thread owns it.
有什么想法吗?