【问题标题】:Design-time DataContext in a DataTemplate?DataTemplate 中的设计时 DataContext?
【发布时间】:2013-06-19 09:47:34
【问题描述】:

当我将DataTemplate 放入<Page.Resources> 部分时,它会在设计器内编辑绑定时继承PageDataContext。但是在运行时DataTemplatePage 中的一个元素使用,该元素拥有自己的DataContext。我希望设计师在绑定时显示内部DataContext

DataTemplates 是否有类似 d:DataContext 的标签?设置DataType 没有任何作用。

【问题讨论】:

    标签: wpf visual-studio-2012 datatemplate datacontext designer


    【解决方案1】:

    我发现您可以在 DataTemplate 内的根元素上设置 d:DataContext

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    
    <ListBox ItemsSource="{Binding People}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel d:DataContext="{d:DesignInstance Type=local:Person}">
                <TextBlock Text="{Binding Name}" />
                <TextBlock Text="{Binding Age}" />
                <TextBlock Text="{Binding Height}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
    

    【讨论】:

      【解决方案2】:

      我意识到这是超级旧的,但为了让 SO 变得更好。 DataTemplates 通过 DataType 标签有一个“DataContext”。

      <DataTemplate DataType="{x:Type local:Person}">
          <StackPanel>
              <TextBlock Text="{Binding Name}" />
              <TextBlock Text="{Binding Age}" />
              <TextBlock Text="{Binding Height}" />
          </StackPanel>
      </DataTemplate>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-06
        • 2016-09-24
        • 1970-01-01
        • 2011-11-27
        • 2013-12-04
        • 2012-12-19
        • 2021-12-21
        相关资源
        最近更新 更多