MyContainer derived from FrameworkElement with binding support.

Posted by alex2k8 on Stack Overflow See other posts from Stack Overflow or by alex2k8
Published on 2009-04-04T22:14:54Z Indexed on 2010/04/06 12:03 UTC
Read the original article Hit count: 239

Filed under:
|

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);
}

© Stack Overflow or respective owner

Related posts about wpf

Related posts about binding