Custom control including wpf TabControl fails bindings with ElementName

300 Views Asked by At

I've a CustomControl which has an Items property. An internal TabControl is bound to it like this:

<Style TargetType="{x:Type local:CustomControl1}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustomControl1}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <TabControl Name="PART_TabControl"
                                >
                    </TabControl>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

OnApplyTemplate:

public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        TabControl tabControl = Template.FindName("PART_TabControl", this) as TabControl;
        foreach (var item in Items)
        {
            Dispatcher.BeginInvoke(new Action(() => tabControl.Items.Add(item)), System.Windows.Threading.DispatcherPriority.ContextIdle);
        }
    }    

To demonstrate the problem I've added "Dispatcher.BeginInvoke". The problem occurs when tabitems are added after a while. The usage below results in a binding failure:

<ccl:CustomControl1 Name="cc1">
        <ccl:TabItemCollection>
            <TabItem Header="Tab1">
                <TextBox Name="txtData" />
            </TabItem>
            <TabItem Header="Tab2">
                <TextBlock Text="{Binding ElementName=txtData, Path=Text}" />
            </TabItem>
        </ccl:TabItemCollection>
    </ccl:CustomControl1>    

I noticed that after snooping the textblock, the problem is fixed. And from the source code I see this code does the job:

BindingExpression expression = BindingOperations.GetBindingExpression(dObj, property);

                if (expression != null && !expression.HasError && expression.Status != BindingStatus.Active)
                {
                    dObj.ClearValue(property);
                    BindingOperations.SetBinding(dObj, property, expression.ParentBindingBase);
                }

As I've many controls in tab items this kind of "fix binding" code causes a lot of performance issues.

Is there any workaround for that?

0

There are 0 best solutions below