2

I have a Datagrid filled with a table. Now the vertical scrollbar shows up because the table doesn't fit. That's fine so far. Now in the last column I have defined a Button in the xaml file. All these buttons have the same callback, but I can distinguish from the selectedIndex of the table what this callback should do. Because clicking the button automatically also selects the line in the DataGrid where this button lives. That's fine so far. Now in my app, for some rows I want to disable the Button, because it has no meaning for that specific row. So what I did is take a subscription on event Load of each Button and let the callback set the MaxWidth = 0, if the button has no meaning. This works fine too, but only initially. As soon as I start dragging the scrollbar, at random places in the Button column buttons show up, or wrong buttons get MaxWidth = 0. I have the strong feeling that cells that scrolled out at the top are being reused at the bottom, but I don't get an event, or at least I don't know which event I should subscribe on. I don't know how to identify the scrollbar. Has anyone a suggestion to tackle this problem?

1 Answer 1

0

I finally found a solution to this problem myself, and I will post it for the record. The event you should subscribe on is LoadingRow (generated by the DataGrid). In the callback

void TableLoadingRow(object sender, DataGridRowEventArgs e)

you can identify an element in a cell by using VisualTreeHelper for instance as follows:

private void ButtonSetMaxWidth(DependencyObject reference, int maxWidth)
{
    if (reference != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(reference); i++)
        {
            var child = VisualTreeHelper.GetChild(reference, i);
            if (child.GetType() == typeof(Button))
            {
                Button b = (Button)child;
                if (b.Name == "TheNameOfTheButtonInTheXAML") 
                {
                    b.MaxWidth = maxWidth;
                    return;
                }
            }
            ButtonSetMaxWidth(child, maxWidth);
        }
    }
    return;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.