WPF Material Design ComboBox Выпуск выпусков - PullRequest
1 голос
/ 09 октября 2019

Я использую MaterialDesignThemes 2.6.0 в приложении WPF Framework 4.6.1.

Если я щелкаю ComboBox в StackPanel, всплывающее окно появляется без прозрачности при первом щелчке:

StackPanel flyout.

Если я нажму на поле со списком в DataGrid, всплывающее окно будет прозрачным:

GridView first click

Я должен нажать еще раз, чтобы показать его правильно:

GridView second click

App.xaml:

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Dark.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.Blue.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.DeepPurple.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

MainWindow.xaml:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:vm="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Background="{DynamicResource MaterialDesignPaper}"
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
      Title="MainWindow" Height="250" Width="400">
    <Window.DataContext>
        <vm:ViewModel/>
    </Window.DataContext>
    <StackPanel>
        <ComboBox ItemsSource="{Binding ComboItems}"/>
        <DataGrid ItemsSource="{Binding ComboItems}"
                  AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Combo" Width="200">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}},
                                                            Path = DataContext.ComboItems}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>
</Window>

ViewModel.cs:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1
{
    public class ViewModel : INotifyPropertyChanged
    {
        private ObservableCollection<string> _comboItems;

        public ObservableCollection<string> ComboItems
        {
            get => _comboItems;
            set
            {
                if (value == _comboItems) return;
                _comboItems = value;
                OnPropertyChanged();
            }
        }

        public ViewModel()
        {
            _comboItems = new ObservableCollection<string>()
            {
                "Item 1",
                "Item 2"
            };
        }

        #region INotify support
        public event PropertyChangedEventHandler PropertyChanged;

        void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        #endregion
    }
}

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

РЕДАКТИРОВАТЬ: я открыл проблему на github

Ответы [ 2 ]

0 голосов
/ 24 октября 2019

У меня тоже была эта проблема. Я думаю, что это ошибка, происходящая из-за обработки прозрачности на фоне другой области. Я нашел решение (на самом деле взломать ;-P) для этого и сделал класс util, сделав фон со списком, чтобы он был непрозрачным при раскрытии раскрывающегося списка и обратно прозрачным при закрытии.

Обновление:

Добавлена ​​задержка в 100 мс, без которой она не работает должным образом.

using System;
using System.Windows.Controls;
using System.Windows.Media;
using System.Threading.Tasks;

namespace LogisticsNote.Utils
{
public class ManageCombo
{
    private static Brush OPAQUE_BACKGROUND_ON_OPEN = Brushes.WhiteSmoke;

    public static void SetBackgroundManagementEvents(params ComboBox[] combo)
    {
        foreach (ComboBox c in combo) SetBackgroundManagementEvents(c);
    }

    public static void SetBackgroundManagementEvents(ComboBox combo)
    {
        combo.DropDownOpened += Combo_DropDownOpened;
        combo.DropDownClosed += (s, e) =>
            (s as ComboBox).Background = Brushes.Transparent;
    }

    private static void Combo_DropDownOpened(object sender, EventArgs e)
    {
        var combo = sender as ComboBox;
        combo.IsDropDownOpen = false;
        if (combo.Items.Count == 0)
        {
            combo.Background = Brushes.Transparent;
            return;
        }

        combo.DropDownOpened -= Combo_DropDownOpened;
        combo.Background = OPAQUE_BACKGROUND_ON_OPEN;
        Task.Delay(100).ContinueWith(_ =>
        {
            combo.Dispatcher.Invoke((Action)(() =>
            {
                combo.IsDropDownOpen = true;
                combo.DropDownOpened += Combo_DropDownOpened;
            }));
        });
    }
}
}

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

Вы можете использовать класс как

ManageCombo.SetBackgroundManagementEvents ( 
    combo1, combo2,      // Set to all combos in UI
    combo3, combo4
);
0 голосов
/ 11 октября 2019
    <!-- Flat ComboBox -->
    <SolidColorBrush x:Key="ComboBoxNormalBorderBrush" Color="Gainsboro" />
    <SolidColorBrush x:Key="ComboBoxNormalBackgroundBrush" Color="White" />
    <SolidColorBrush x:Key="ComboBoxDisabledForegroundBrush" Color="#888" />
    <SolidColorBrush x:Key="ComboBoxDisabledBackgroundBrush" Color="Gainsboro" />
    <SolidColorBrush x:Key="ComboBoxDisabledBorderBrush" Color="#888" />

    <ControlTemplate TargetType="ToggleButton" x:Key="ComboBoxToggleButtonTemplate">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition Width="20" />
            </Grid.ColumnDefinitions>
            <Border Grid.ColumnSpan="2" Name="Border"
                    BorderBrush="{StaticResource ComboBoxNormalBorderBrush}" 
                    CornerRadius="4" BorderThickness="0" 
                    Background="{StaticResource ComboBoxNormalBackgroundBrush}" >
            </Border>
            <Border Grid.Column="1" Margin="0" BorderBrush="WhiteSmoke" Name="ButtonBorder"
                    CornerRadius="4" BorderThickness="0, 0, 0, 0" 
                    Background="{StaticResource ComboBoxNormalBackgroundBrush}" >

            </Border>

            <Path Name="Arrow" Grid.Column="1" 
                    Data="M0,0 L0,2 L4,6 L8,2 L8,0 L4,4 z"
                    HorizontalAlignment="Center" Fill="Gray"
                    VerticalAlignment="Center" />
        </Grid>
        <ControlTemplate.Triggers>
            <Trigger Property="UIElement.IsMouseOver" Value="True">
                <Setter Property="Panel.Background" TargetName="ButtonBorder" Value="WhiteSmoke"/>
            </Trigger>
            <Trigger Property="ToggleButton.IsChecked" Value="True">
                <Setter Property="Panel.Background" TargetName="ButtonBorder" Value="WhiteSmoke"/>
                <Setter Property="Shape.Fill" TargetName="Arrow" Value="#FF8D979E"/>
            </Trigger>
            <Trigger Property="UIElement.IsEnabled" Value="False">
                <Setter Property="Panel.Background" TargetName="Border" Value="{StaticResource ComboBoxDisabledBackgroundBrush}"/>
                <Setter Property="Panel.Background" TargetName="ButtonBorder" Value="{StaticResource ComboBoxDisabledBackgroundBrush}"/>
                <Setter Property="Border.BorderBrush" TargetName="ButtonBorder" Value="{StaticResource ComboBoxDisabledBorderBrush}"/>
                <Setter Property="TextElement.Foreground" Value="{StaticResource ComboBoxDisabledForegroundBrush}"/>
                <Setter Property="Shape.Fill" TargetName="Arrow" Value="#999"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>

    <Style TargetType="{x:Type ComboBox}">
        <Setter Property="IsEditable" Value="False"/>
        <Setter Property="IsTextSearchEnabled" Value="True"/>
        <Setter Property="IsTextSearchCaseSensitive" Value="False"/>
        <Setter Property="Margin" Value="3"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
        <Setter Property="HorizontalAlignment" Value="Stretch"/>
        <Setter Property="FontSize" Value="12"/>
        <Setter Property="StaysOpenOnEdit" Value="True"/>
        <Setter Property="SelectedValuePath" Value="Content"/>
        <Setter Property="UIElement.SnapsToDevicePixels" Value="True"/>
        <Setter Property="FrameworkElement.OverridesDefaultStyle" Value="True"/>
        <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
        <Setter Property="ScrollViewer.CanContentScroll" Value="True"/>
        <Setter Property="TextElement.Foreground" Value="Black"/>
        <Setter Property="IsDropDownOpen" Value="False"/>
        <Setter Property="MinHeight" Value="23"/>

        <Setter Property="FrameworkElement.FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate TargetType="ComboBox">
                    <Grid>
                        <ToggleButton Name="ToggleButton" Grid.Column="2"
                                ClickMode="Press" Focusable="False"
                                IsChecked="{Binding Path=IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
                                Template="{StaticResource ComboBoxToggleButtonTemplate}"/>

                        <ContentPresenter Name="ContentSite" Margin="5, 3, 23, 3" IsHitTestVisible="False"
                                HorizontalAlignment="Left" VerticalAlignment="Center"                              
                                Content="{TemplateBinding ComboBox.SelectionBoxItem}" 
                                ContentTemplate="{TemplateBinding ComboBox.SelectionBoxItemTemplate}"
                                ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"/>
                        <TextBox Name="PART_EditableTextBox" Margin="3, 3, 23, 3"                     
                                IsReadOnly="{TemplateBinding IsReadOnly}"
                                Visibility="Hidden" Background="Transparent"
                                HorizontalAlignment="Left" VerticalAlignment="Center"
                                Focusable="True">
                            <TextBox.Template>
                                <ControlTemplate TargetType="TextBox" >
                                    <Border Name="PART_ContentHost" CornerRadius="4" Focusable="False" />
                                </ControlTemplate>
                            </TextBox.Template>
                        </TextBox>
                        <!-- Popup showing items -->
                        <Popup Name="Popup" Placement="Bottom"
                                Focusable="False" AllowsTransparency="True"
                                IsOpen="{TemplateBinding ComboBox.IsDropDownOpen}"
                                PopupAnimation="Slide" SnapsToDevicePixels="True">
                            <Border Name="DropDownBorder" Background="WhiteSmoke" Margin="0, 1, 0, 0"
                                            CornerRadius="4" BorderThickness="0" 
                                            BorderBrush="{StaticResource ComboBoxNormalBorderBrush}">

                                <Grid Name="DropDown" SnapsToDevicePixels="True"
                                        MinWidth="{TemplateBinding FrameworkElement.ActualWidth}"
                                        MaxHeight="{TemplateBinding ComboBox.MaxDropDownHeight}" Background="Transparent" Margin="0">

                                    <ScrollViewer Margin="4" SnapsToDevicePixels="True">
                                        <ItemsPresenter KeyboardNavigation.DirectionalNavigation="Contained" />
                                    </ScrollViewer>
                                </Grid>
                            </Border>

                        </Popup>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="ItemsControl.HasItems" Value="False">
                            <Setter Property="FrameworkElement.MinHeight" TargetName="DropDownBorder" Value="95"/>
                        </Trigger>
                        <Trigger Property="UIElement.IsEnabled" Value="False">
                            <Setter Property="TextElement.Foreground" Value="{StaticResource ComboBoxDisabledForegroundBrush}"/>
                        </Trigger>
                        <Trigger Property="ItemsControl.IsGrouping" Value="True">
                            <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>
                        </Trigger>
                        <Trigger Property="ComboBox.IsEditable" Value="True">
                            <Setter Property="KeyboardNavigation.IsTabStop" Value="False"/>
                            <Setter Property="UIElement.Visibility" TargetName="PART_EditableTextBox" Value="Visible"/>
                            <Setter Property="UIElement.Visibility" TargetName="ContentSite" Value="Hidden"/>
                        </Trigger>

                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <!-- End of Flat ComboBox -->
...