A.R.
A.R.

Reputation: 15704

WPF Canvas items and DataTemplate

Is there a way that I can use non-UIElements in a canvas if I have a DataTemplate (or something similar) for them? I feel like I have done this before, and that it is possible, but I can't figure it out. Here is some code...

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

Upvotes: 2

Views: 4548

Answers (2)

Ra&#250;l Ota&#241;o
Ra&#250;l Ota&#241;o

Reputation: 4770

Your problem here is that you cant add model items to a Panel, just UI elements. For to do this that you want, you need to do some like this:

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

Your resources, and:

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

Try this, and also you may set the X and Y properties from the model, setting the ItemsContainerStyle. Hope this works for you...

Upvotes: 2

Rachel
Rachel

Reputation: 132618

Wrap them in a ContentPresenter or ContentControl, which are controls that can host any object type in their Content

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

The ContentPresenter will draw the item using your implicit DataTemplate automatically

Upvotes: 4

Related Questions