MyContainer derived from FrameworkElement with binding support.
- by alex2k8
To understand how the binding works, I implemented MyContainer derived from FrameworkElement. This container allowes to set Children and adds them into the logical tree. But the binding by ElementName does not work. What can I do with MyContainer to make it work, leaving the parent as FrameworkElement?
C#:
public class MyContainer : FrameworkElement
{
public MyContainer()
{
Children = new List<FrameworkElement>();
}
public List<FrameworkElement> Children { get; set; }
protected override IEnumerator LogicalChildren
{
get { return Children.GetEnumerator(); }
}
}
XAML:
<Window x:Class="WpfLogicalTree.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfLogicalTree"
Title="Window1" Height="300" Width="300">
<StackPanel>
<local:MyContainer>
<local:MyContainer.Children>
<TextBlock Text="Foo" x:Name="_source" />
<TextBlock Text="{Binding Path=Text, ElementName=_source}" x:Name="_target"/>
</local:MyContainer.Children>
</local:MyContainer>
<Button Click="Button_Click">Test</Button>
</StackPanel>
</Window>
Window1.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(_target.Text);
}