Question

we have a rather odd requirement: The visibility of any control in our WPF-Application is to be driven by a database-table.

That means we have a table which stores the name of the element and its visiblity.

Now I am looking for an elegant way to implement this feature on the client side.

I could create my own UserControl and inherit from it everywhere, providing a InitializeComponent Template Method. But what if someone programmatically adds more childcontrols?

I don't want my controls to know about this mechanism at all. I want to hook in/intercept at a certain point (pre control-rendering) and adjust the visibility of the control according to the database.

Is that somehow possible? And if not, how would you design it?

Was it helpful?

Solution

So here is what I did:

I inherited from UserControl and put the check in the an EventHandler for the Loaded Event.

I then let my Controls inherit from my CustomControl, this works pretty well.

The FindName() implementation won't find the FrameworkElements for some reason I don't know, although their names are defined in the xaml. So here is the routine I use to find the children by their names:

    public static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            string controlName = child.GetValue(Control.NameProperty) as string;

            if (controlName == name)
            {
                return child as T;
            }
            else
            {
                T result = FindVisualChildByName<T>(child, name);
                if (result != null)
                {
                    return result;
                }
            }
        }

        return null;
    }

I don't like this solution but it works.

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