Wpf customcontrol how to bind button click inside itemscontrol DataTemplate

I have a custom control that inherits from Textbox, in .cs I have DependencyProperty SelectedItems (these items will appear inside the texbox if any) if the texbox doesn't look like a normal texbox.

In generic.xaml in Template I added new border and inside I put ItemsControl with item template like this

xaml itemControl:

<Border BorderBrush="Green" BorderThickness="1">
                        <ItemsControl x:Name="PART_SelectedItemsHost"
                                ItemsSource="{TemplateBinding SelectedItems}"
                                ItemTemplate="{TemplateBinding SelectedItemsTemplate}"
                                Margin="{TemplateBinding Padding}"
                                    <WrapPanel IsItemsHost="True">


Xaml ItemTemplate part:

<DataTemplate x:Key="DefaultSelectedItemsTemplate" >
    <Border x:Name="selectedItemBorder" BorderBrush="Gray" BorderThickness="1" CornerRadius="5" Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" Margin="5,1,1,1">
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="15"/>
            <TextBlock Grid.Column="0" Text="{Binding}" Margin="5,0,3,0"></TextBlock>
            <Button BorderThickness="0" Grid.Column="1" Click="???" or Command="???" >X</Button>


Now how can I bind this "X" button in my .cs file. I am trying to do this by overriding the OnApplyTemplate () method ... and I was able to bind the mousedown when I click on the texbox element, but I donโ€™t know how to attach this click on the button

my.cs part

            public override void OnApplyTemplate()
        ItemsControl itmControl = GetTemplateChild("PART_SelectedItemsHost") as ItemsControl;

        if (itmControl != null)
            itmControl.MouseLeftButtonDown += new MouseButtonEventHandler(itmControl_MouseLeftButtonDown);

            // blind click on X buttons in ItemsControl


    private void itmControl_MouseLeftButtonDown(object obj, MouseButtonEventArgs e)
        //IsMouseLeftButtonDown = true;
        object item = (e.OriginalSource as FrameworkElement).DataContext;



and here is a picture of how this control looks like ant so that the X button removes the item from the SelectedItem collection.



source to share

1 answer

The ItemsControl has the following name:

<ItemsControl x:Name="PART_SelectedItemsHost"


So in the template

<Button  BorderThickness="0" Grid.Column="1" Command="{Binding DataContext.DeleteItem, ElementName=PART_SelectedItemsHost}" CommandParameter="{Binding}">X</Button>




All Articles