简体   繁体   中英

Accessing children of UserControl at design time

Windows 8 Style Apps (ex. "Metro"), Visual Studio 2012, XAML.

I have a UserControl derived from Canvas. It has one child element - a Polygon with its Data bound to a property (with INotifyPropertyChanged implemented):

<Canvas x:Name="MyPolygon">
    <Polygon Points="{Binding ElementName=MyPolygon,Path=MyPoints}" ... />
</Canvas>

The property is set and the Polygon is correctly rendered, both at design-time and run-time, if I instantiate that control elsewhere in XAML, passing in a string:

<local:MyPolygon MyPoints="..." />

However, changing the values in that string is tedious. A designer would prefer to have a collection of some UI knots (like Ellipses) visible at design-time but invisible at run-time, so that they could drag them in the designer and have the Polygon reconstruct its geometry on the fly:

<local:MyPolygon>
    <Ellipse Canvas.Left="204" Canvas.Top="57" ... />
    <Ellipse Canvas.Left="166" Canvas.Top="30" ... />
    ...
</local:MyPolygon>

Basically I want to keep the geometry information in (extended) .Children. Is this possible?

(There could be some event/constructor where the control could examine its .Children (after those Ellipses are inserted), retrieve their coordinates, and build MyPoints. The designer would have to trigger that event for the geometry to be visible at design time)

Have you looked at design data like this .

if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
{
    GetSampleData();
}
else GetRealData();

or

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

<CollectionViewSource
  x:Name="groupedItemsViewSource"
  Source="{Binding Groups}"
  IsSourceGrouped="true"
  ItemsPath="Items"
  d:Source="{Binding ItemGroups, 
    Source={d:DesignInstance Type=data:SampleDataSource, 
      IsDesignTimeCreatable=True}}"/>

So, I ended up creating a Polygon on the same level where I have the Ellipses.

<Polygon Points="{Binding ElementName=MyPoints,Converter={StaticResource PolygonConverter}}" ... />
<Canvas x:Name="MyPoins">
    <Ellipse Canvas.Left="228" Canvas.Top="69" ... />
    <Ellipse Canvas.Left="166" Canvas.Top="30" ... />
    ...
</Canvas>

The binding converter converts coordinates of all .Children of the object to a string.

This works at both design time and run time.

Unfortunately, one must rebuild the project after moving the Ellipses around in order for VS designer to refresh the view and pick up the changes, which makes the design process much less intuitive than it could have been. :/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM