我在代码中使用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。你能告诉我为什么这可能吗?
答案 0 :(得分:1)
使用MyListBox
代替ListBox
,将您的课程范围从private
更改为public
,然后相应地更改您的XAML:
<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
,那么在这种情况下不一定有必要。