【发布时间】:2012-09-14 17:15:39
【问题描述】:
我正在尝试实现此处显示的示例 [WPF Canvas, how to add children dynamically with MVVM code behind],但是当我启动我的程序时没有显示任何内容(即使 Canvas 的 IsItemHost 设置为 True。
我的应用程序是由实体类型组成的:
public class Entity
{
public Entity(int x, int y, int width, int height)
{
X = x;
Y = y;
Width = width;
Height = height;
}
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}
实体存储在 EntitiesCollection 中:
public class EntitiesCollection : ObservableCollection<Entity>
{
public EntitiesCollection()
{
Add(new Entity(10, 10, 10, 10));
Add(new Entity(50, 20, 25, 25));
}
}
Wich 是 DrawingViewModel 类的成员:
public class DrawingViewModel
{
public DrawingViewModel()
{
Entities = new EntitiesCollection();
}
public EntitiesCollection Entities;
}
我的应用程序的 DataContext 在 MainWindow.xaml.cs 中设置:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new DrawingViewModel();
}
}
MainWindow.xaml 文件本身看起来像这样:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test" Height="350" Width="525" Icon="Graphics/Icons/paint.png">
<Grid>
<ItemsControl ItemsSource="{Binding Entities}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas IsItemsHost="True"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding X}"/>
<Setter Property="Canvas.Top" Value="{Binding Y}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Red" BorderThickness="1" Width="{Binding Width}" Height="{Binding Height}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
怎么了?谢谢。
【问题讨论】:
-
顺便说一下,
Entity应该要么不提供公共设置器/根本不提供设置器和private readonly支持字段,要么实现INotifyPropertyChanged。这样要么属性根本不更改,要么通知 UI 更改。 -
将字段转换为属性并没有解决问题:启动程序时没有出现任何内容。我同意 INotifyPropertyChanged,但这只是第一步 :)
-
那么你有绑定错误吗?
-
我对绑定调试还很陌生,但是当我只是在调试模式下启动程序时没有提到任何内容。
-
你读过我链接的文章吗?您不会从失败的绑定中得到任何异常...
标签: wpf mvvm observablecollection itemscontrol