Search code examples
wpfitemscontrol

ElementName binding for items in a custom ItemsControl


I'm looking to create a custom ItemsControl where the nested items use ElementName binding to another control. For the standard ItemsControl this works fine and the binding works as expected

<ItemsControl>
    <TextBox Text="{Binding Text, ElementName=test, UpdateSourceTrigger=PropertyChanged}"/>
</ItemsControl>
<TextBox x:Name="test"/>

However, as soon as I come to use a custom control inheriting from ItemsControl as follows

<!-- CustomItemsControl.xaml -->
<ItemsControl x:Class="MyControl.CustomItemsControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"/>

<!-- CustomItemsControl.xaml.cs -->
namespace MyControl
{
    public partial class CustomItemsControl 
    {
        public CustomItemsControl()
        {
            InitializeComponent();
        }
    }
}

<!-- Window.xaml -->
<local:CustomItemsControl>
    <TextBox Text="{Binding Text, ElementName=test, UpdateSourceTrigger=PropertyChanged}"/>
</local:CustomItemsControl>
<TextBox x:Name="test"/>

Then the ElementName binding is no longer working. Has anyone else seen this issue and know how to resolve it?

Any help greatly appreciated.


Solution

  • Why do you need the xaml file for your CustomControl. You just need to create a class in your local namespace like this which inherits from ItemsControl-

    public class CustomItemsControl : ItemsControl
        {
    
        }
    

    And it should work as desired..!!