WPF combobox предотвращает обновление выбора - PullRequest
0 голосов
/ 11 июня 2018

У меня есть ComboBox, который выглядит следующим образом:

enter image description here

Я не хочу, чтобы значение ... изменилоськогда выбран один из элементов.

Я пробовал множество различных решений - различные привязки на SelectedIndex, SelectedValue, SelectionChanged, играя с IsEditable, IsReadonly, IsHitTestVisible, делая ... фактическим элементом, делая его заполнителем и т. Д. И т. Д. И т. П.

Каждый раз, когда я выбираю элемент, ... обновляется с использованием дочернего значения.Я хочу, чтобы он не изменился.

Как я могу запретить комбинированному списку автоматически обновлять текст при выделении, но при этом иметь возможность выбрать вариант?


Если это поможетвот пользовательский шаблон для этого изображения:

<ResourceDictionary
    x:Class="ComboBoxA"
    xmlns:local="clr-namespace:MyTemplates"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ControlTemplate x:Key="ComboBoxA" TargetType="{x:Type ComboBox}">
        <Grid>
            <ToggleButton 
                ClickMode="Press" 
                Focusable="false"
                IsChecked="{Binding Path=IsDropDownOpen,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"
                Name="ToggleButton" 
            >
                <ToggleButton.Template>
                    <ControlTemplate>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition />
                                <ColumnDefinition Width="36" />
                            </Grid.ColumnDefinitions>

                            <Border
                                x:Name="Border" 
                                Grid.ColumnSpan="2"
                                CornerRadius="0"
                                BorderThickness="1" />
                            <Border 
                                Grid.Column="0"
                                CornerRadius="0" 
                                Margin="1" 
                                Background="Transparent" 
                                BorderThickness="0"
                            />
                            <Path 
                                x:Name="Arrow"
                                Grid.Column="1"     
                                Fill="#707070"
                                HorizontalAlignment="Center"
                                VerticalAlignment="Center"
                                Visibility="Collapsed"
                                Data="M0,0 L8,0 L4,4 z"
                            />
                            <TextBlock 
                                Margin="4,6" 
                                Foreground="#282828" 
                                Grid.Column="0" 
                                Text="{Binding Path=(local:ComboBoxAHelper.Placeholder), RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}}" 
                            />
                        </Grid>

                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="true">
                                <Setter TargetName="Arrow" Property="Visibility" Value="Visible"/>
                                <Setter TargetName="Border" Property="BorderBrush" Value="#d9d9d9"/>
                            </Trigger>

                            <Trigger Property="ToggleButton.IsChecked" Value="true">
                                <Setter TargetName="Arrow" Property="Visibility" Value="Visible"/>
                                <Setter TargetName="Border" Property="BorderBrush" Value="#d9d9d9"/>
                            </Trigger>

                            <DataTrigger Binding="{Binding Path=(local:ComboBoxAHelper.ShowBorders), RelativeSource={RelativeSource TemplatedParent}}" Value="True">
                                <Setter TargetName="Arrow" Property="Visibility" Value="Visible"/>
                                <Setter TargetName="Border" Property="BorderBrush" Value="#d9d9d9"/>
                            </DataTrigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </ToggleButton.Template>
            </ToggleButton>

            <ContentPresenter 
                Content="{TemplateBinding SelectionBoxItem}"
                ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
                ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"
                HorizontalAlignment="Left" 
                IsHitTestVisible="False"  
                Margin="3,3,23,3"
                Name="ContentSite" 
                VerticalAlignment="Center"
            />

            <Popup 
                AllowsTransparency="True" 
                Focusable="False"
                IsOpen="{TemplateBinding IsDropDownOpen}"
                Name="Popup"
                PopupAnimation="Slide"
             >
                <Grid Name="DropDown"
                    MaxHeight="{TemplateBinding MaxDropDownHeight}"
                    MinWidth="{TemplateBinding ActualWidth}"
                    SnapsToDevicePixels="True"                
                >
                    <Border 
                        Background="White"
                        BorderBrush="#d9d9d9"
                        BorderThickness="1"
                        x:Name="DropDownBorder"
                    />
                    <ScrollViewer Margin="4,6" SnapsToDevicePixels="True">
                        <StackPanel 
                            IsItemsHost="True" 
                            KeyboardNavigation.DirectionalNavigation="Contained" 
                        />
                    </ScrollViewer>
                </Grid>

                <Popup.Style>
                    <Style TargetType="Popup">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=(local:ComboBoxAHelper.RightAlignPopup), RelativeSource={RelativeSource TemplatedParent}}" Value="True">
                                <Setter Property="Placement" Value="Left" />
                                <Setter Property="VerticalOffset" Value="{Binding ActualHeight, RelativeSource={RelativeSource TemplatedParent}}" />
                                <Setter Property="HorizontalOffset" Value="{Binding ActualWidth, RelativeSource={RelativeSource TemplatedParent}}" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Popup.Style>
            </Popup>
        </Grid>
    </ControlTemplate>

    <Style x:Key="ComboBoxAItem" TargetType="{x:Type TextBlock}">
        <Setter Property="FontSize" Value="12" />
        <Setter Property="Foreground" Value="#282828" />
        <Setter Property="Padding" Value="4" />
    </Style>
</ResourceDictionary>

... и соответствующий ему XAML:

<ComboBox 
    templates:ComboBoxAHelper.Placeholder="..."
    templates:ComboBoxAHelper.RightAlignPopup="True"
    templates:ComboBoxAHelper.ShowBorders="True"
    HorizontalAlignment="Right" 
    IsReadOnly="True"
    IsEditable="False"
    SelectedValue="x:Null"
    Template="{StaticResource ComboBoxA}" 
>
    <ComboBoxItem>
        <TextBlock Style="{StaticResource ComboBoxAItem}">Close</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock Style="{StaticResource ComboBoxAItem}">Delete</TextBlock>
    </ComboBoxItem>
</ComboBox>

1 Ответ

0 голосов
/ 11 июня 2018

Хитрость заключалась в том, чтобы удалить

 Content="{TemplateBinding SelectionBoxItem}"

из шаблона (как в целом, так и код, размещенный в вопросе).


Благодаря ответу @ shadow32 на мой отдельный вопрос https://stackoverflow.com/a/50805408/385273.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...