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>
我在堆栈面板中有两个控件(control1 和 control2),并且一次我只想显示其中一个控件。 如代码所示,控件的可见性由“IsDateReadOnly”和“CanShowDateControl”驱动。 而且,根据我的视图模型逻辑... CanShowDateControl = !IsReadOnly。
因此,我一次只会显示两个控件之一。
问题:我的问题是,虽然我一次只显示一个控件,但我的 xaml 正在创建两个控件的实例。是否可以仅创建我所显示的控件的实例?
给出:
1)我想使用绑定来显示/隐藏,以便逻辑位于我的视图模型中。 2)我可以将这两个控件保留在一个包装控件内。因为我在不同的地方使用它。
感谢您的关注。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
ContentControl
和ContentTemplateSelector
与两个DataTemplate
结合使用。一种用于只读
,另一种用于非只读
。在选择器中,根据属性返回适当的
DataTemplate
。您可以采用的其他方法是创建一个
自定义控件
,它具有两个(如果超过两个,则更多)属性来存储两个控件。根据条件,它应该将其中一个添加到Visual Tree
中,这将阻止加载另一个。Use a
ContentControl
andContentTemplateSelector
with twoDataTemplate
s. One forReadOnly
and other forNot 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 theVisual Tree
which will prevent the other one from being loaded.