【问题标题】:How do I know when the content of ContentControl is loaded when changing更改时如何知道何时加载 ContentControl 的内容
【发布时间】:2011-05-22 20:56:43
【问题描述】:

我有一个 ContentControl,其内容由基于属性 Workspace 的 DataTemplateSelector 确定。但是当数据模板发生变化时,我必须根据ContentControl的初始大小和整个Window做一些计算,所以我想知道它是什么时候加载的。

<ContentControl Content="{Binding Path=Workspace}" ContentTemplateSelector="{StaticResource workspaceTemplateSelector}" />

资源字典:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                    xmlns:vw="clr-namespace:Capgemini.Sag.KeyEm.View">

    <DataTemplate x:Key="keyboardTemplate"  >
        <vw:Keyboard/>
    </DataTemplate>

    <DataTemplate x:Key="welcomeTemplate">
        <vw:Welcome/>
    </DataTemplate>

    <vw:WorkspaceTemplateSelector            
        KeyboardTemplate="{StaticResource keyboardTemplate}"             
        WelcomeTemplate="{StaticResource welcomeTemplate}"        
        x:Key="workspaceTemplateSelector"/>
</ResourceDictionary>

数据模板选择器:

using Capgemini.Sag.KeyEm.ViewModel.Interfaces;

namespace Capgemini.Sag.KeyEm.View
{
    using System.Windows;
    using System.Windows.Controls;

    class WorkspaceTemplateSelector : DataTemplateSelector
    {
        public DataTemplate WelcomeTemplate { get; set; }
        public DataTemplate KeyboardTemplate { get; set; }

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            if (item is IWelcomeViewModel)
                return WelcomeTemplate;
            if (item is IKeyboardViewModel)
                return KeyboardTemplate;
            return null;
        }
    }
}

【问题讨论】:

  • 处理这个问题的正确方法是回答你自己的问题,然后在几天后选择它作为正确答案。

标签: c# wpf wpf-controls binding


【解决方案1】:

您可以做的一件事是将数据模板内容包装在容器中并监听加载的事件

<DataTemplate x:Key="keyboardTemplate">
        <Grid Loaded="Grid_Loaded">
            <vw:Welcome/>
        </Grid>
    </DataTemplate>

切换模板时将引发加载的事件。希望这会有所帮助。

【讨论】:

  • Grid_Loaded 必须在 ResourceDictionary 的代码隐藏中。但是计算在使用 ResourceDictionary 的窗口中。我该如何解决?
  • 检查这是否有帮助stackoverflow.com/questions/92100/…
  • 我现在如何将代码隐藏添加到 ResourceDictionary。但是我如何传达父窗口的宽度?
猜你喜欢
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 2017-01-11
  • 1970-01-01
相关资源
最近更新 更多