System.Linq.GroupBy Key not binding in silverlight

余生颓废 提交于 2019-12-19 19:45:15

问题


list.ItemsSource=db.Templates.GroupBy(t=>t.CategoryName);

in xaml:

<DataTemplate>
   <TextBlock Text="{Binding Key}" />
</DataTemplate>

After this code. Don't show any text in TextBlock. I'm changing Text binding like this

<DataTemplate>
   <TextBlock Text="{Binding}" />
</DataTemplate>

TextBlock Text shown like this System.Linq.Lookup^2+Grouping[System.String,Model.Template]

I'm debugging and checking Key property. this is not null.

Why Key don't bind in TextBlock?

How to show group title in Textblock?


回答1:


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 });



回答2:


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}}" />


来源:https://stackoverflow.com/questions/8342720/system-linq-groupby-key-not-binding-in-silverlight

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