Sorry for the wordy title - I am battling to work out if my problems are caused by
- Bad class design (likely)
- Ignorance (very likely)
- Both (most likely)
I have spent ages googling but due to not really understanding my problem it's harder to find the solution.
Basically, I have a "Day" class which has an ObservableCollection of Period called Periods. Each period has a length of time. I have a method/property of my Day class (TotalTimeUpUnTilThisPeriod) that takes in a period and returns the amount of time of all the periods up until that point.
I need to put this Period level though so that my datagrid can bind to it (it's itemssource is set to Day.Periods and it's datacontext is set to Day). However, I have to do the calculation in Day as Period instances don't know anything about their siblings and it feels wrong if a child walked up the tree to parent level and summed the children.
My thinking is this - a period should have no "state" ie. no idea of where it is in the day in relation to it's siblings - this is the job of the Day class.
So, if my class design is correct - then how can I access the datacontext in a bound datacolumn? I tried to write a converter that would take in a period and then get the parent datacontext (Day) and call my method to return a string to bind to at period level) but I could not figure out how to make my converter aware of the datagrid datacontext and I want to know if I am on the right track.
This is probably bad design but I considered replicating the parent property (e.g. TotalTimeUpUnTilThisPeriod) in the child class (Period) and then somehow setting it whenever a duration changed just so that I could bind to it but it got really messy.
Periods can be added/removed from the datagrid/Day so it can't be calculated on rowload - it has to be dynamic (I guess I could use LINQ to sum the lengths of all previous periods)
So I think my questions are:
- Is my class design above ok? (ie. the children should know nothing of the parent or their fellow siblings?)
- If so, then how do you bind to parent properties or methods in a datagrid if a value is dependent on the state of the parent?
Thanks for any pointers.
UPDATE:
Here are some more things I have tried in the cold light of day:
1) Text= "{Binding DataContext.SomeTextField, ElementName=LayoutRoot}"
This does not work - it works fine when outside the datagrid but not when inside.
2) I tried setting the DataContext of a textbox in a templated DataGrid column - this works well, but then I need to pass in the row datacontext AND the parent datacontext to a Converter (in order to lookup the total time for all periods before this one) and I can't figure out how to do that.
So another question may be - How do you pass in the the current row datacontext to a converter AND the parent datacontext (or just "how to make a converter aware of the parent datacontext").