Dependency属性作为对话框初始目录多线程问题

时间:2016-03-29 04:05:08

标签: c# wpf multithreading dialog dependency-properties

我正在使用依赖项属性创建文件选择器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.

有什么想法吗?

0 个答案:

没有答案
相关问题