how to link container and its contents?
i have an object based on ContentControl type and I want to embed custom controls into its content. below is the code.
the problem is that i need MyContainer to have a list of MyControl objects so that it can communicate to them, and each MyControl will need a reference to its MyContainer.
how is this done properly? one way that i see is to declare an attached property on MyControl and set it to 开发者_Go百科the name of the MyContainer object, but this seems redundant because MyCOntrol objects can search the visual tree to find the container. if searching is the right way to do this, where would i place the code that does the search? in MyControl constructor?
thanks for any input konstantin
public class MyContainer : ContentControl
{
...
}
public class MyConrol : Control
{
...
}
<c:MyContainer>
<Grid>
<c:MyControl />
</Grid>
</c:MyContainer>
You can add property MyControls
to MyContainer
class, create a template for MyContainer
with a list in it (ItemsControl
, ListBox
or some other list control), put the list itself inside the grid from your sample code, bind the list's ItemsSource
to MyControls
property.
To get container for the control in XAML, you can use binding with RelativeSource set to FindAncestor.
If you need to find container from code, you should probably do it every time or cache the value on the first use (can controls be moved to another container?). Contructor is not the appropriate place, because first control is created and only then it is put into the tree.
Attached properties are definitely unnecessary.
精彩评论