2012-10-12 182 views
1

如果我有一个DataTemplate(或类似的东西),我可以在画布中使用非UIElements吗?我觉得我以前做过这件事,而且这是可能的,但我无法弄清楚。下面是一些代码...WPF画布项目和DataTemplate

<Window x:Class="EntityTranslator.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:EntityTranslator" 
     Title="MainWindow" Height="350" Width="525"> 

    <Window.Resources> 
    <local:Entity x:Key="DesignEntity}" EntityName="Test" /> 

    <DataTemplate DataType="{x:Type local:Entity}"> 
     <StackPanel> 
     <TextBlock Text="{Binding Name}"/> 
     </StackPanel> 
    </DataTemplate> 
    </Window.Resources> 

    <Grid> 
    <Canvas> 
     <local:Entity EntityName="Test" /> 
    </Canvas> 
    </Grid> 
</Window> 
+0

有你的尝试过吗? 我没有看到为什么这不应该工作 –

+0

@eranotzer当然我试过了,这是代码,抱怨'本地:实体'不是一个UIElement,这是帆布的期望。 –

回答

1

这里你的问题是,你不能添加模型项到面板,只是UI元素。为了做到这一点,你想要的,你需要做一些这样的:

<Window.Resources> 
     <DataTemplate DataType="{x:Type WpfApplication2:Entity}"> 
      <StackPanel> 
       <TextBlock Text="{Binding EntityName}"/> 
      </StackPanel> 
     </DataTemplate> 
    </Window.Resources> 

你的资源,以及:

 <ListBox ItemsSource={Binding SomeEntityCollection}> 
      <ListBox.ItemsPanel> 
       <ItemsPanelTemplate> 
        <Canvas/> 
       </ItemsPanelTemplate> 
      </ListBox.ItemsPanel> 
     </ListBox> 

试试这个,而且你也可以设置为从X和Y属性模型,设置ItemsContainerStyle。希望这对你有用...

+0

这是完美的!我可以开始做生意,不必费心去整理一些内容主持人。 –

3

总结他们在ContentPresenterContentControl,这是可以在任何主机对象类型控制他们的Content

<ContentPresenter> 
    <local:Entity EntityName="Test" /> 
</ContentPresenter> 

ContentPresenter将使用隐式绘制项目DataTemplate自动

+0

这是开始让我去哪里我需要去... –