开发者

Conditional loading of WPF controls

开发者 https://www.devze.com 2023-02-03 16:00 出处:网络
Given: <StackPanel> <View:ArcController x:Name=\"control1\" Visibility=\"{Binding Path=CanShowDateControl, Converter={StaticResource bool2VisibilityConverter}}\"/>

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}}"  />

 开发者_JAVA百科       </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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号