Skip to main content
 首页 » 编程设计

c#之WPF Canvas 项和 DataTemplate

2024年02月20日18xxx_UU

如果我有一个 DataTemplate(或类似的东西),我可以在 Canvas 中使用非 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> 

请您参考如下方法:

将它们包裹在 ContentPresenter 中或 ContentControl ,它们是可以在其 Content

中承载任何对象类型的控件
<ContentPresenter> 
    <local:Entity EntityName="Test" /> 
</ContentPresenter> 

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