I have a custom UserControl with a custom DependencyProperty. To paint a better picture of how I’m using this, the UserControl is the left navigation indicator in a wizard-like control. The left nav control exists inside of each of the controls that represent a step in the wizard. Inside of the left nav control, I am toggling visibility and setting visual properties of several child controls with a few converters with code similar to the following. I can’t use a simple style selector or style-selecting converter because the entire structure of each row in my StackPanel is different if the item is selected or not.
This is a ton of code to be repeating all over my control to bind to a single custom property. Is there a shorter form version of the following or a cleaner way to implement this?
<Polygon
Visibility="{Binding
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=UserControl},
Path=Selected,
Converter={StaticResource myCustomConverter},
ConverterParameter='Expected String'}">
...
The parent views supply a single property to customize the child control:
<!-- Left Column -->
<views:LeftNavControl Selected="Item to Select..." />
There are some things you could do, but I would not describe them as neither a cleaner/shorter way to implement it. They are fairy easy to implement if you are using a
MVVMapproach.The first thing you could do is getting rid of the
RelativeSource/AncestorTypein your bindings to find the location of the bound property.If both/all your controls (it’s not clear how many controls you use) would share the same viewmodel you could bound the same viewmodel property to
views:LeftNavControl.Selected, and to all of your toggled visibility controls.The second thing you could do, is a more radical approach that would clean your xaml, and it will also make your
myCustomConverterobsolete, but will move some of the business logic in your viewmodel. This works best in case you have a multitude ofPolygons/other controls that need visibility toggle.You could have a
StepXVisiblityproperty in your viewmodel, and you could calculate it every timeviews:LeftNavControl.Selectedchanges and your Polygon(s) xaml will look like:A simple example of the above explanation would be:
ViewModel: