2
我想在这里实现[WPF Canvas, how to add children dynamically with MVVM code behind]所示的例子,但没有显示当我启动我的程序(甚至IsItemHost设置为True画布。问题用帆布的ItemsControl
我提出申请
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是AA 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>
有什么不对?谢谢。
顺便说一下,'实体'应该或者根本不提供公共setter /没有setter和'private只读'后台字段或实现['INotifyPropertyChanged'](http:// msdn。 microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx)。因此,属性完全不会改变,或者UI被通知更改。 –
将字段转换为Property不能解决问题:启动程序时不显示任何内容。我同意INotifyPropertyChanged,但这只是第一步:) – thomasc
那么你有任何绑定错误? –