此代码运行良好:
private void Combobox1_Loaded(object sender, RoutedEventArgs e)
{
var combo = (ComboBox)sender;
var pointGroupList = (List<PointGroup>)combo.ItemsSource;
combo.ItemsSource = pointGroupList.Select(group => group.Name);
}但这个根本没用:
private void Combobox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var combo = (ComboBox)sender;
var pointGroupList = (List<PointGroup>)combo.ItemsSource;
textBlock1.Text = "num of points:" + pointGroupList.Find(group => group.Name == (string)combo.SelectedItem).PointsCount.ToString();
}下面是输出窗口中的消息:
无法将'WhereSelectListIterator2Autodesk.Civil.DatabaseServices.PointGroup,System.String‘类型的对象转换为'System.Collections.Generic.List1Autodesk.Civil.DatabaseServices.PointGroup'.类型在_01_COGO_Points.ModalDialog_1.Combobox1_SelectionChanged(Object发件人,SelectionChangedEventArgs e),D:\00 Materials\c3d\c#\examples\ACAD\01 COGO Points\Window.xaml.cs:line 49
任何帮助都将不胜感激。
发布于 2018-12-18 00:29:56
您在Loaded事件中所做的事情非常奇怪。我不建议这样做,因为它会破坏你的绑定。如果您这样做的原因是Name属性显示在您的ComboBox中,那么您应该使用DataTemplate。就像这样:
<Window.Resources>
<DataTemplate x:Key="pntGroupTemplate" DataType="{x:Type ac:PointGroup}">
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</Window.Resources>当然,您需要在窗口中添加一个命名空间。就像这样:
xmlns:ac="clr-namespace:Autodesk.Civil.DatabaseServices;assembly=AeccDbMgd"我没有民事法庭,所以不确定这是否正确,但应该是接近的。如果这条路径不太正确,Intellisense应该能够帮助您找到正确的路径。
在你的通讯箱里,
<ComboBox ItemTemplate="{StaticResource pntGroupTemplate}" ... />我的最佳建议是完全摆脱Combobox1_Loaded事件处理程序中的所有代码,并在xaml中创建一个DataTemplate,使用上面的代码片段显示Name属性。最后,将lambda表达式更改为:
group => group.Name == (string)combo.SelectedItem对此:
group => group.Name == (combo.SelectedItem as PointGroup)?.Name你得到的例外是由于第二行。当您在加载事件中调用Select方法时,它返回IEnumerable<string>,所以当您将ItemsSource转换为List<PointGroup>时,一切都会以许多不同的方式发生:-)。
您正在做的另一个问题是,现在,SelectedItem是一个string,并且没有Name属性。
希望这有帮助
https://stackoverflow.com/questions/53824045
复制相似问题