Manish Basantani
Manish Basantani

Reputation: 17509

Conditional loading of 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 a stackpanel, and at one time i want to show only one of the controls. As shown in the code, the visibility of the controls is driven by "IsDateReadOnly" and "CanShowDateControl". And, as per my viewmodel logic... CanShowDateControl = !IsReadOnly.

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

Question: My problem is, though i am showing only one control at a time, my xaml is creating instance of both the controls. Is it possible to create instance of only the control that i am showing?

Give that:

1) I want to show/hide using binding, so that logic lies in my viewmodel. 2) I can keep these two controls inside one wrapper control. Since i am using it at different places.

Thanks for your interest.

Upvotes: 3

Views: 1233

Answers (1)

decyclone
decyclone

Reputation: 30840

Use a ContentControl and ContentTemplateSelector with two DataTemplates. One for ReadOnly and other for Not ReadOnly.

In the selector, based on the property, return appropriate DataTemplate.

Other way you could go is create a Custom Control which has two (or more if more than two) properties to store two controls. Based on a condition, it should add one of them to the Visual Tree which will prevent the other one from being loaded.

Upvotes: 3

Related Questions