WPF控件的加载条件 [英] Conditional loading of WPF controls

查看:359
本文介绍了WPF控件的加载条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设:

        <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>         



我有两个控制(控制1和控制2)一的StackPanel里面,在同一时间,我想只显示控制中的一个。
以在代码所示,控件的可见性是由IsDateReadOnly和CanShowDateControl驱动。
和,按我的视图模型逻辑... CanShowDateControl =!IsReadOnly。

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.

问:我的问题是,虽然我一次显示只有一个控制,我的XAML是创建两个控件的实例。难道只有我显示的控件创建实例?

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?

给出如下:

1)我想用绑定来显示/隐藏,这样的逻辑就在于我视图模型。
2)我可以保持一个包装里面的控制这两个控件。因为我用它在不同的地方。

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.

感谢您的关注。

推荐答案

使用 ContentControl中 ContentTemplateSelector 有两个的DataTemplate 秒。一个用于只读等为不是只读

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

在选择的基础上,属性,则返回相应的的DataTemplate

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.

这篇关于WPF控件的加载条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆