【发布时间】:2015-12-11 00:13:06
【问题描述】:
编辑 2:这是问题的原始版本。进行了其他修订,但这是唯一正确显示问题的修订。
类似问题:
- How to use WPF to visualize a simple 2D world (map and elements)
- How to convert X/Y position to Canvas Left/Top properties when using ItemsControl
- How to display items in Canvas through Binding
正如上面的第一个问题,我正在尝试构建一个 2D 世界。我的精灵恰好是表示为 XAML 文件的矢量图形,但我怀疑这是否重要。无论如何,除了白色背景之外,我什么也得不到。
我尝试将我的精灵直接添加到 XAML 中的画布中,效果很好,但我需要通过程序生成它们。我查看了 Snoop 中的窗口,发现画布实际上并没有渲染。它只是窗口本身。
为什么我的精灵没有出现?
MainWindow.xaml
<Window x:Class="Canvas_test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Self"
Title="MainWindow" Height="350" Width="525">
<ItemsControl ItemsSource="{Binding Sprites, ElementName=Self}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding X}" />
<Setter Property="Canvas.Top" Value="{Binding Y}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
</Window>
MainWindow.xaml.cs
using System.Collections.ObjectModel;
using System.Windows;
namespace Canvas_test {
public partial class MainWindow : Window {
public ObservableCollection<Character> Sprites { get; private set; } = new ObservableCollection<Character>();
public MainWindow() {
InitializeComponent();
Sprites.Add(new Character());
}
}
}
Character.xaml
<Viewbox x:Class="Canvas_test.Character"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="64"
Height="64"
Stretch="Uniform">
<Canvas Width="64" Height="64">
<Ellipse xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="64" Height="64" Fill="#FF0000FF"/>
<Path xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Fill="#FFFF0000" Data="M 32 0 64 66.25 l -64 0 z" RenderTransform="0.5 0 0 0.9 16 0" />
</Canvas>
</Viewbox>
Character.xaml.cs
using System.Windows.Controls;
namespace Canvas_test {
public partial class Character : Viewbox {
public double X { get; } = 100;
public double Y { get; } = 100;
}
}
【问题讨论】:
-
1) 您的主窗口没有DataContext,您可以从Snoop 中看到存在数据绑定错误。 2) 您正在向您的 ViewModel 添加一个视图...请尝试解决该问题并告诉我们发生了什么。