简体   繁体   中英

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM