views:

317

answers:

3

Hi All,

Assuming I have this struct definition in C#:

 public struct TimeSlotInfo
 {
  public int TimeSlotID;
  public int StartMin;
  public int CalcGridColumn;
  public string BackgroundCol;
  public bool ToDisable;
 }

And I have a linq query as so:

var TimeSlotsInfo = 
from ts in datacon.TimeSlots
select new TimeSlotInfo
{
    TimeSlotID = ts.TimeSlotID,
    StartMin = ts.StartMin,
    CalcGridColumn = CalcTimeSlotGridColumn(ts.StartMin),
    BackgroundCol = ts.ColorName,
    ToDisable = false
};

If i set the ItemsSource property of say a ListBox as below:

lstBox.ItemsSource = TimeSlotsInfo;

Now, how do i set a binding path to reference the "BackgroundCol" field from the above query result?

I've tried {Binding Path=TimeSlotInfo.BackgroundCol}, {Binding Path=TimeSlotInfo/BackgroundCol}, and finally {Binding Path=BackgroundCol}...none of them seem to be working..

Can anyone help? I've tried to simplify the example as possible. Hope my problem is clear enough. Thanks in advance.

A: 

If you want your items to display whatever is stored in BackgroundCol, you can just set the DisplayMemberPath property on your ListBox to "BackgroundCol". If this isn't what you're trying to achieve, please be more specific.

Hope this helps!!

Pwninstein
Ah, I didn't know that - I don't think that's what's going wrong here (as I post in my reply), but that's a cool shortcut.
Paul Betts
+5  A: 

The last one is correct ({Binding Path=BackgroundCol}) - however, you can't bind to fields, you can only bind to Properties. Define your class to be:

class TimeslotInfo {
    public int TimeslotId {get; set;}
    /* Etc... */
}
Paul Betts
I JUST thought of this and was about to edit my above post to include it. +1, you're right!
Pwninstein
+3  A: 

Not only should you use properties for binding as Paul says, but in general you should avoid public fields in the first place.

In addition, this doesn't feel like it should be a struct - do you really want value-type semantics? When in doubt, you should default to creating classes in C# - it's pretty rare that you really want a struct.

Finally, even if you did want a struct, you should almost always make structs immutable. You're almost certain to have unexpected results from mutable structs. It's all well defined and for good reasons, but it's probably not the behaviour you expect. Mutable structs are evil.

Jon Skeet
Aren't you even losing any possible benefit of structs, when you run it through LINQ? (i.e. they'll all be boxed anyways?)
Paul Betts
Why would they be boxed? The compiler knows the appropriate type to use.
Jon Skeet