Reputation: 270
I have custom control that inherit from Textbox, in .cs i have DependencyProperty SelectedItems (those items will show inside texbox if there is any) if not texbox looks like normal texbox.
In generic.xaml in Template i added new border and inside i put ItemsControl with item template like this
xaml itemControl part:
<Border BorderBrush="Green" BorderThickness="1">
<ItemsControl x:Name="PART_SelectedItemsHost"
ItemsSource="{TemplateBinding SelectedItems}"
ItemTemplate="{TemplateBinding SelectedItemsTemplate}"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Margin="{TemplateBinding Padding}"
Visibility="Visible">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True">
</WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Border>
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">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="15"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding}" Margin="5,0,3,0"></TextBlock>
<Button BorderThickness="0" Grid.Column="1" Click="???" or Command="???" >X</Button>
</Grid>
</Border>
</DataTemplate>
Now how can i bind that button "X" in my .cs file .. i am trying to do this overriding OnApplyTemplate() method ... and i did manage to bind mousedown when i click on item texbox but i dont know how to attach that click on button
my .cs part
public override void OnApplyTemplate()
{
base.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;
System.Diagnostics.Debug.WriteLine(e.OriginalSource.ToString());
object item = (e.OriginalSource as FrameworkElement).DataContext;
deleteSelectedItem(item);
}
and here is picture how this control looks like ant that X button need to delete item from SelectedItem collection.
Upvotes: 3
Views: 1824
Reputation: 3232
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>
Upvotes: 1