我在代码中使用ListBox来存储用户选择的某些csv文件:

<ListBox x:Name="emailsFilesListBox" HorizontalAlignment="Left" Height="67" Margin="10,254,0,0" Grid.Row="1" VerticalAlignment="Top" Width="147"/>


在MainWindow.xaml.cs中,我使用私有类来扩展System.Windows.Controls.ListBox:

private class MyListBox : System.Windows.Controls.ListBox
        {
            public string[] FullFilesPathsList { get; set; }
            public MyListBox() : base()
            {
            }
        }


在MainWindow.xaml.cs的事件处理程序中,我具有以下代码:

  private void emailsAdd_Click(object sender, RoutedEventArgs e)
    {
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        dlg.Multiselect = true;
        dlg.Filter = "CSV Files|*.csv";
        Nullable<bool> result = dlg.ShowDialog();

        if (result == true)
        {
            MyListBox myListBoxWithEmailsFiles = new MyListBox();
            myListBoxWithEmailsFiles = (MyListBox)emailsFilesListBox;
            myListBoxWithEmailsFiles.FullFilesPathsList = dlg.FileNames;
            ....................................

        }
    }


尝试执行转换“ myListBoxWithEmailsFiles =(MyListBox)emailsFilesListBox;”导致InvalidCastException。你能告诉我为什么这可能吗?

最佳答案

通过将类的范围从MyListBox更改为ListBox,然后相应地更改XAML,使用private代替public

<nameOfYourWpfProject:MyListBox x:Name="emailsFilesListBox"
    HorizontalAlignment="Left" Height="67" Margin="10,254,0,0" Grid.Row="1"
    VerticalAlignment="Top" Width="147"/>


您必须在主Window标签中添加以下内容:

xmlns:nameOfYourWpfProject="clr-namespace:NameOfYourWpfProject"




通常,您不能将基本类型转换为这样的派生类型。另一种选择是将ctor中的ListBox传递给您的类,然后创建属性以公开要访问的ListBox属性。

private class MyListBox : System.Windows.Controls.ListBox
{
    public string[] FullFilesPathsList { get; set; }

    public MyListBox(ListBox listBox)
    {
        this.listBox = listBox;
    }

    private ListBox listBox;

    public string Name { get { return listBox.Name; } }
}


如果仅使用MyListBox代替ListBox,在这种情况下就没有必要了。

10-04 21:11