Binding Geometry properties in an ItemsControl
In a Silverlight game I'm working on I'm using an ItemsControl
to display an ObservableCollection
of game objects that we'll call Foo
. Foo
implements INotifyPropertyChanged
and has a single property: Radius
. The ItemsControl
's ItemTemplate
represents each Foo
as an circular path, with the radius of the path bound to Foo.Radius
.
The problem I'm running into is that whenever I try to add something to the ObservableCollection
I get an InvalidOperationException
with the message "Operation is not valid due to the current state of the object." If a remove the RadiusX
and RadiusY
bindings program runs fine, and it still works if I bind Foo.Radius
to some prop开发者_运维百科erty of Path
. I'm at a loss for how to bind the geometry properties. Am I missing something?
XAML for reference:
<ItemsControl ItemsSource="{Binding}" x:Name="LayoutRoot">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Path Stroke="Black">
<Path.Data>
<EllipseGeometry RadiusX="{Binding Radius}" RadiusY="{Binding Radius}" />
</Path.Data>
</Path>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Codebehind:
private ObservableCollection<Foo> things = new ObservableCollection<Foo>();
public MainPage()
{
InitializeComponent();
LayoutRoot.DataContext = things;
CompositionTarget.Rendering += Update;
}
void Update(object sender, EventArgs e)
{
things.Add(new Foo());
}
Try this ...
Dispatcher.BeginInvoke(() => things.Add(new Foo()));
I did a bit more searching and discovered that in Silverlight 3 it's only possible to bind properties to FrameworkElement
s, but Geometry
inherits from DependencyObject
. Upgrading the project to Silverlight 4 seemed to fix the problem.
精彩评论