Edit 2: This is the original version of the question. Other revisions were made, but this is the only one which properly shows the problem.
Similar questions:
- 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
As in the first question above, I'm trying to build a 2D world. My sprites happen to be vector graphics expressed as XAML files, but I doubt that matters. Anyway, I can't get anything beyond a white background.
I tried adding my sprites directly to the canvas in XAML, and that worked fine, but I need them procedurally generated. I looked at the window in Snoop and saw that the canvas isn't actually rendering at all; it's just the window itself.
Why aren't my sprites showing up?
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;
}
}