开发者

Multiple Cast from DataGrid

I'm having a bit of problem with casting and datagrids. I have a LINQ to SQL query:

var contents = from content in context.Contents
               join contenttype in context.ContentTypes on content.ContentTypeID equals contenttype.ContentTypeID
               select new { content, contenttype };

and then that gets put into a datagrid (not all of the data, only select columns such as content.ContentID etc).

The problem is that when I try and get the selected row, I cannot. I h开发者_StackOverflowave the following code:

Console.WriteLine((Content)dataGrid1.SelectedItem);

which fails due to the fact that the type is both Content and ContentType - is there a way around this? The error I get is:

Unable to cast object of type '<>f__AnonymousType0`2[iAdvert_Desktop.Content,iAdvert_Desktop.ContentType]' to type 'iAdvert_Desktop.Content'.

If I just write the SelectedItem I get: { content = iAdvert_Desktop.Content, contenttype = iAdvert_Desktop.ContentType } - is there a way I can do something like: (Content)dataGrid1.SelectedItem['Content'];?


I think this post may answer your question: How do I get values from SelectedItem in ComboBox with Linq and C# 3.5


In WPF, you never need to use SelectedItem. You'd better redesign this so you use a collection view instead.


SelectedItem is not "both Content and ContentType", it's an anonymous type that has properties called Content and ContentType.

Why not spool up a little poco class that has the two properties you'd like and return one of those instead?

public class YourPocoClass
{
   public whateverContentIs Content { get; set; }
   public whateverContentTypeIs ContentType { get; set; }
}

var contents = from content in context.Contents
               join contenttype in context.ContentTypes on content.ContentTypeID equals contenttype.ContentTypeID
               select new YourPocoClass() {Content = content, ContentType = contenttype };


Console.WriteLine(((YourPocoClass)dataGrid1.SelectedItem).Content);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜