Reputation: 1293
I am trying to set properties of buttons inside of a layout grid. The grid itself is dynamically generated and so are the buttons inside of the grid cells. Unfortunately I cannot reference anything by name in code.
I need to refernce the buttons based on the grid cell they are in. I tried using the following code.
stackButton = (Button) (from buttons in rowGrid.Children
where Grid.GetColumn (buttons as FrameworkElement) == s.RoomCol
where Grid.GetRow (buttons as FrameworkElement) == s.RoomRow
select buttons).FirstOrDefault();
The "stackButton" control is a Button control. "s" is a custom control that holds coordinates for the button within the grid. I do not get any objects returned when that code executes. Any ideas how I can better execute this?
Upvotes: 1
Views: 655
Reputation: 3052
Short answer:
Not without getting creative (see below). That's basically the only way because of how attached properties work.
Aside
Two things though... stylistically, instead of two where clauses, you can use && You can technically have two controls share the same row/column (in which case they are superimposed, so you may want to rethink "firstordefault"
Full answer: YES
If you wanted to get super clever, you could register your own attached dependency properties like: Grid.MyRow
and Grid.MyColumn
and give them an OnChanged
handler, which would:
Grid.SetRow
(or column)add your control to a dictionary, keyed with row, column. ie: make your own class that has Row
and Column
, implement Equals
, and GetHashCode
, so you can do this:
Dictionary _buttons = new Dictionary();
OnChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { // snip _dict.Add(new GridKey(row, column), button); }
Then your lookup becomes a O(1) operation instead of O(n)
If you don't want to go the attached properties route, you can simply do the _dict.Add thing when you dynamically generate the grid. (when you do rowGrid.Children.Add(..)
)
If you can't do that, then you can have a method which iterates through the children once and adds them all to the dictionary, so that further lookups are O(1)
Upvotes: 1