System.Linq.GroupBy Key not binding in silverlight

女生的网名这么多〃 提交于 2019-12-01 17:54:21
RobSiklos

Hmmm - unfortunate. The reason is because the result of the GroupBy() call is an instance of System.Linq.Lookup<,>.Grouping. Grouping is a nested class of the Lookup<,> class, however Grouping is marked as internal.

Security restrictions in Silverlight don't let you bind to properties defined on non-public types, even if those properties are declared in a public interface which the class implements. The fact that the object instance you are binding to is of a non-public concrete type means that you can only bind to public properties defined on any public base classes of that type.

You could build a public shim class to act as a view model for the grouping:

public class MyGrouping {
  public string Key {get; internal set;}
}

list.ItemsSource=db.Templates.GroupBy(t=>t.CategoryName)
                             .Select(g => new MyGrouping { Key = g.Key });

It's been a while, but I had similar problem recently, so I decided to post another solution.

You can create a converter and return the value of Key from it

public class GroupNameToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var grouping = (IGrouping<string, [YOUR CLASS NAME]>) value;

            return grouping.Key;
        }

    }

and in Xaml you don't bind to Key, but to the grouping itself.

<TextBlock Text="{Binding Converter={StaticResource groupNameToStringConverter}}" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!