JackMF
JackMF

Reputation: 13

How to set Combobox dropdown list width to the Combobox it belongs to?

See picture below, how to align dropdown list border to the actual combo box?

https://i.sstatic.net/nCktj.jpg

Here is the code for Combobox, which uses customized ComboBoxItem style,

<ComboBox Grid.Row="0" Grid.Column="0" ItemsSource="{Binding ASDevicesView, Mode=OneWay , UpdateSourceTrigger=PropertyChanged}"  AutomationProperties.AutomationId="4314"
                      SelectedItem="{Binding SDevice}" IsEditable="True" Text="{Binding SearchText}" MaxDropDownHeight="166" ItemContainerStyle="{StaticResource MyComboBoxItemStyle}">
    <ComboBox.Style>
        <Style TargetType="{x:Type ComboBox}">
            <Style.Triggers>
                <Trigger Property="IsKeyboardFocusWithin" Value="True">
                    <Setter Property="IsDropDownOpen" Value="true" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
</ComboBox>

Here is the code for ComboBoxItem style,

<Style x:Key="MyComboBoxItemStyle" BasedOn="{StaticResource {x:Type ComboBoxItem}}" TargetType="{x:Type ComboBoxItem}">
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="VerticalContentAlignment" Value="Center" />
    <Setter Property="RenderOptions.ClearTypeHint" Value="Enabled" />
    <Setter Property="Width" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ActualWidth}" />
    <Setter Property="Height" Value="40" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ComboBoxItem">
                <Grid Background="Transparent" >
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="36"/>
                        <ColumnDefinition Width="AUTO"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="AUTO"/>
                    </Grid.RowDefinitions>
                    <Image Source="{Binding Icon}" Width="12" Height="12" Margin="3,3,3,3" Grid.Row="0" Grid.Column="0"/>
                    <TextBlock Text="{Binding DName}" Grid.Row="0" Grid.Column="1" HorizontalAlignment="Left"  VerticalAlignment="Center" FontWeight="Bold"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Upvotes: 1

Views: 272

Answers (1)

user10794413
user10794413

Reputation:

I think the problem is that the ComboBox is not the TemplatedParent of the ComboBoxItem (indeed it was pointed out e.g. in this comment), so better to search it explicitly:

<Setter Property="Width" Value="{Binding 
    RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}, Path=ActualWidth}" />

Upvotes: 1

Related Questions