How to align to the right X buttons in the WPF Combobox?
What I got is this:
Xaml:
<ComboBox ItemsSource="{Binding Entities}"
SelectedItem="{Binding SelectedEntity}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding EntityName, Mode=OneWay}"
VerticalAlignment="Center"/>
<Button Grid.Column="1" HorizontalAlignment="Right"
Command="{Binding DataContext.DeleteEntityCommand,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">
<Image Source="..\Resources\DeleteIcon.png" HorizontalAlignment="Center" />
</Button>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Entities
is an ObservableCollection
of some Entity
class.
Do I have to use something else instead of Grid
?
One more question:
if user clicked on the X button of some item then it has to be passed to DeleteEntityCommand
(using CommandParameter
maybe). How to do it? SelectedItem
of ComboBox
is still AAAAAA, not HHHH (see the pic).
The Problem is, that your Grid in the Template isnt stretched across the available space. According to this Post it can be achieved with
<ComboBox>
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ComboBox.ItemContainerStyle>
<ComboBox.ItemTemplate>
<DataTemplate>
//etc.
Note: If you dont define the width of your Button it will be stretched across the remaining space. I Suggest to add a Columndefinition with Width=Auto and add the Button there (Grid.Column=2).
Edit
The additionaly column is meant to be a filler like this (left) because your Buttons may stretch themself across the available space (right).
Second Question
You can set the Commandparameter of a Command and if im not mistaken, the Item itself can be passed with {Binding}.
<Button Command={Binding ...} Commandparameter={Binding}/>
And the ICommand implementation must be extended/overloaded to accept Parameter.