我在将ObservableCollection绑定到画布时遇到了一些困难。
XAML:
<ScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible">
<local:DesignerCanvas x:Name="designerCanvas" AllowDrop="True">
<ItemsControl ItemsSource="{Binding Circles}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
<Button Canvas.Left="452" Canvas.Top="487" Content="Button" Height="23" Name="button1" Width="75" Click="button1_Click" />
</local:DesignerCanvas>
</ScrollViewer>
注意:DesignerCanvas只是从Canvas派生的类。我已经覆盖了MeasureOverride函数,使其正确调整大小以使滚动查看器显示出来。
代码背后:
public partial class LogicView : UserControl
{
private ObservableCollection<Shape> circles;
public ObservableCollection<Shape> Circles
{
get { return circles; }
set { circles = value; }
}
...
public void DrawCircle()
{
Ellipse ellipse = new Ellipse();
SolidColorBrush brush = new SolidColorBrush(Brushes.Blue.Color);
ellipse.Fill = brush;
ellipse.StrokeThickness = 2;
ellipse.Stroke = Brushes.Black;
ellipse.Width = 100;
ellipse.Height = 100;
DesignerCanvas.SetLeft(ellipse, 100);
Circles.Add(ellipse);
}
}
DrawCircle函数向ObservableCollection添加一个椭圆,但画布上没有任何内容。似乎绑定工作不正常。可能是什么问题?
答案 0 :(得分:1)
如果您使用的是Caliburn Micro,请替换
ItemsSource="{Binding Circles}"
到
Name="Circles"
将解决您的问题