WPF中如何实现标签页控件的惰性绑定? [英] How to Achieve Lazy Binding of Tab Page Controls in WPF?

查看:34
本文介绍了WPF中如何实现标签页控件的惰性绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体类.这个实体有很多属性,实体的数据在一个TabControl 的几个TabItems 中显示给用户.我还实现了 MVVM 方法.

I have an entity class. This entity has lots of properties and entity's data is shown to the user in several TabItems of a TabControl. I also implement MVVM approach.

当屏幕首先显示给用户时,我只想绑定活动标签页控件,当用户浏览标签页时,将根据需要产生额外的单独绑定.我怎样才能做到这一点?

When the screen is shown to the user first, I want to bind only the active tab page controls and as the user navigates through tab pages additional separate bindings will be incurred as-needed. How can I achieve that?

推荐答案

您无事可做,这是默认行为.TabItem 内容的 DataTemplate 不会被实例化,直到这个 TabItem 被选择

You don't have anything to do, that's the default behavior. The DataTemplate for a TabItem content won't be instantiated until this TabItem is selected

这是一个例子:

<Window.Resources>
    <DataTemplate DataType="{x:Type vm:Page1ViewModel}">
        <v:Page1View />
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:Page3ViewModel}">
        <v:Page3View />
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:Page3ViewModel}">
        <v:Page3View />
    </DataTemplate>
</Window.Resources>

...

<TabControl ItemsSource="{Binding Pages}"
            DisplayMemberPath="Title">
</TabControl>

在上面的代码中,TabControl 将根据项目类型选择适当的 DataTemplate,并且仅在该项目被选中时才呈现它.

In the code above, the TabControl will pick the appropriate DataTemplate based on the item type, and will render it only when that item is selected.

编辑 2:显然您想在多个页面上显示单个 ViewModel 的数据.如果你想让每个 TabItem 的控件延迟实例化,你需要使用每个 TabItemContentTemplate 属性:

EDIT 2: apparently you want to display the data of a single ViewModel on several pages. If you want the controls of each TabItem to lazily instantiated, you need to use the ContentTemplate property of each TabItem:

<TabControl>
    <TabItem Header="Page 1">
        <TabItem.ContentTemplate>
            <DataTemplate>
                <v:Page1View />
            </DataTemplate>
        </TabItem.ContentTemplate>
    </TabItem>
    <TabItem Header="Page 2">
        <TabItem.ContentTemplate>
            <DataTemplate>
                <v:Page2View />
            </DataTemplate>
        </TabItem.ContentTemplate>
    </TabItem>
    <TabItem Header="Page 3">
        <TabItem.ContentTemplate>
            <DataTemplate>
                <v:Page3View />
            </DataTemplate>
        </TabItem.ContentTemplate>
    </TabItem>
</TabControl>

这篇关于WPF中如何实现标签页控件的惰性绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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