可以说我有一个Listbox
<ListBox ItemsSource="{Binding MyList}"/>
Run Code Online (Sandbox Code Playgroud)
我有一个属性:
private List<dynamic> _myList;
public List<dynamic> MyList
{
get { return _myList; }
set
{
if(value==null)return;
_myList = value;
OnPropertyChanged();
}
}
Run Code Online (Sandbox Code Playgroud)
好的,现在我们得到了我的问题:我有几个类,我将有列表,我希望能够在这个ListBox中显示它们.
类别:
public class A
{
public string S { get; set; }
public int I { get; set; }
}
public class B
{
public int C { get; set; }
public string Name { get; set; }
public string F { get; set; }
}
public class C
{
public int I { get; set; }
public string Name { get; set; }
public string This { get; set; }
public double That { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
填写myList
private void FillA()
{
List<A> listA = GetListAFromSomewhere();
MyList = listA;
}
private void FillB()
{
List<B> listb = GetListBFromSomewhere();
MyList = listb;
}
private void FillC()
{
List<C> listC = GetListCFromSomewhere();
MyList = listC;
}
Run Code Online (Sandbox Code Playgroud)
我得到了例外
无法将类型'System.Collections.Generic.List'隐式转换为'System.Collections.Generic.List'
我试图施放,并寻找转换器.但似乎无法弄明白.当我换到时,它也会这样做List<object>.
这个
谢谢您的帮助!
And*_*rew 10
我认为你的问题是由协方差/控制引起的.类不支持此功能.您可以使用interface或Cast linq方法.在这里查看更多:https://msdn.microsoft.com/en-us/library/ee207183.aspx 我的意思是这样的:
MyList = GetListAFromSomewhere().Cast<dynamic>().ToList();
Run Code Online (Sandbox Code Playgroud)
还不确定您的ListBox是否可以正常使用动态.您可以在XAML中使用继承和TemplateSelector:http://www.codeproject.com/Articles/418250/WPF-Based-Dynamic-DataTemplateSelector