2

如果我有一个 DataTemplate (或类似的东西),有没有一种方法可以在画布中使用非 UIElements?我觉得我以前做过这个,这是可能的,但我想不通。这是一些代码...

<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>
4

2 回答 2

4

将它们包装在ContentPresenterContentControl中,它们是可以在其内部托管任何对象类型的控件Content

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

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

于 2012-10-12T19:19:54.950 回答
2

您的问题是您不能将模型项添加到面板,而只能添加 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。希望这对你有用...

于 2012-10-12T19:28:04.453 回答