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.

Was it helpful?


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... */


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.

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!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top