Conditionally load WPF controls

Given:

        <StackPanel>      
<View:ArcController x:Name="control1" Visibility="{Binding Path=CanShowDateControl, Converter={StaticResource bool2VisibilityConverter}}"  />
<my1:DateLabelView x:Name="control2" DataContext="{Binding Path=DateLabelViewModel}" Visibility="{Binding ElementName=ctrlTableToolbar, Path=DataContext.IsDateReadOnly, Converter={StaticResource bool2VisibilityConverter}}"  />

        </StackPanel>         

I have two controls (control1 and control2) inside the stack panel, and at one point I want to show only one control. As shown in the code, the visibility of the controls is controlled by "IsDateReadOnly" and "CanShowDateControl". And according to my viewmodel logic ... CanShowDateControl =! IsReadOnly.

So, at one time, I will ONLY show one of the two controls.

Question: My problem is that while I show only one control, my xaml instantiates both controls. Is it possible to instantiate only the control that I am showing?

Give this:

1) I want to show / hide the use of binding, so the logic lies in my view model. 2) I can save these two controls inside one wrapper control. Since I use it in different places.

Thank you for your interest.

+3
source share
1 answer

Use ContentControland ContentTemplateSelectortwo DataTemplates. One for ReadOnlyand another for Not ReadOnly.

In the property-based selector, return the appropriate one DataTemplate.

Another way you could go is to create Custom Controlone that has two (or more, if more than two) properties to hold two controls. Based on the condition, he must add one of them to Visual Tree, which will prevent the other from loading.

+3

Source: https://habr.com/ru/post/1784948/


All Articles