編輯2:這是問題的原始版本。其他修訂已經完成,但這是唯一能正確顯示問題的修訂。另一個WPF畫布不顯示數據綁定元素
類似的問題:
- 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添加視圖...請嘗試解決該問題並告訴我們發生了什麼。 – tgpdyk