2013-07-30 5 views
1

Я создаю приложение WPF, и у меня есть шаблон управления, определенный в App.XAML для combobox.Шаблон управления WPF не применяется к визуализированному первому элементу

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

Что мне не хватает?

Вот App.xaml:

<Application x:Class="WpfPropertyGrid_Demo.App" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
StartupUri="MainWindow.xaml"> 
<Application.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 

          <ResourceDictionary> 
           <!--Brushes defined here--> 
          </ResourceDictionary> 


          <ResourceDictionary> 
           <ControlTemplate x:Key="ComboBoxToggleButton" TargetType="ToggleButton"> 
            <Grid> 
             <Grid.ColumnDefinitions> 
              <ColumnDefinition /> 
              <ColumnDefinition Width="20" /> 
             </Grid.ColumnDefinitions> 
             <Border 
              Grid.ColumnSpan="2" 
              Background="{StaticResource WindowBackgroundBrush}" /> 
              <Border 
               x:Name="Border" 
               Grid.Column="1" 
               Background="{StaticResource WindowBackgroundBrush}" /> 
               <Path 
                x:Name="Arrow" 
                Grid.Column="1"  
                Fill="{StaticResource GlyphBrush}" 
                HorizontalAlignment="Center" 
                VerticalAlignment="Center" 
                Data="M 0 0 L 4 4 L 8 0 Z"/> 
               </Grid> 
               <ControlTemplate.Triggers> 
                <Trigger Property="ToggleButton.IsMouseOver" Value="true"> 
                 <Setter TargetName="Border" Property="Background" Value="{StaticResource ActiveBrush}" /> 
                </Trigger> 
                <Trigger Property="ToggleButton.IsChecked" Value="true"> 
                 <Setter TargetName="Border" Property="Background" Value="{StaticResource ActiveBrush}" /> 
                 <Setter TargetName="Arrow" Property="Fill" Value="{StaticResource ActiveGlyphBrush}" /> 
                </Trigger> 
                <Trigger Property="IsEnabled" Value="False"> 
                 <Setter TargetName="Border" Property="Background" Value="{StaticResource DisabledBackgroundBrush}" /> 
                 <Setter TargetName="Border" Property="BorderBrush" Value="{StaticResource DisabledBorderBrush}" /> 
                 <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/> 
                 <Setter TargetName="Arrow" Property="Fill" Value="{StaticResource DisabledForegroundBrush}" /> 
                </Trigger> 
               </ControlTemplate.Triggers> 
              </ControlTemplate> 

              <ControlTemplate x:Key="ComboBoxTextBox" TargetType="TextBox"> 
               <Border x:Name="PART_ContentHost" Focusable="False" Background="{TemplateBinding Background}" /> 
              </ControlTemplate> 

              <Style x:Key="{x:Type ComboBox}" TargetType="ComboBox"> 
               <Setter Property="SnapsToDevicePixels" Value="true"/> 
               <Setter Property="OverridesDefaultStyle" Value="true"/> 
               <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/> 
               <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/> 
               <Setter Property="ScrollViewer.CanContentScroll" Value="true"/> 
               <Setter Property="MinHeight" Value="20"/> 
               <Setter Property="Template"> 
                <Setter.Value> 
                 <ControlTemplate TargetType="ComboBox"> 
                  <Grid> 
                   <ToggleButton 
                    Name="ToggleButton" 
                    Template="{StaticResource ComboBoxToggleButton}" 
                    Grid.Column="2" 
                    Focusable="false" 
                    IsChecked="{Binding Path=IsDropDownOpen,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}" 
                    ClickMode="Press"> 
                   </ToggleButton> 
                   <ContentPresenter 
                    Name="ContentSite" 
                    IsHitTestVisible="False" 
                    Content="{TemplateBinding SelectionBoxItem}" 
                    ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" 
                    ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" 
                    Margin="3,3,23,3" 
                    VerticalAlignment="Center" 
                    HorizontalAlignment="Left" /> 
                    <TextBox x:Name="PART_EditableTextBox" 
                     Style="{x:Null}" 
                     Template="{StaticResource ComboBoxTextBox}" 
                     HorizontalAlignment="Left" 
                     VerticalAlignment="Center" 
                     Margin="3,3,23,3" 
                     Focusable="True" 
                     Background="Transparent" 
                     Visibility="Hidden" 
                     IsReadOnly="{TemplateBinding IsReadOnly}"/> 
                     <Popup 
                      Name="Popup" 
                      Placement="Bottom" 
                      IsOpen="{TemplateBinding IsDropDownOpen}" 
                      AllowsTransparency="True" 
                      Focusable="False" 
                      PopupAnimation="Slide"> 
                      <Grid 
                       Name="DropDown" 
                       SnapsToDevicePixels="True"     
                       MinWidth="{TemplateBinding ActualWidth}" 
                       MaxHeight="{TemplateBinding MaxDropDownHeight}"> 
                       <Border 
                        x:Name="DropDownBorder" 
                        Background="{StaticResource ActiveBrush}" /> 
                        <ScrollViewer Margin="4,4,4,4" SnapsToDevicePixels="True"> 
                         <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" /> 
                        </ScrollViewer> 
                       </Grid> 
                      </Popup> 
                     </Grid> 
                     <ControlTemplate.Triggers> 
                      <Trigger Property="HasItems" Value="false"> 
                       <Setter TargetName="DropDownBorder" Property="MinHeight" Value="95"/> 
                      </Trigger> 
                      <Trigger Property="IsEnabled" Value="false"> 
                       <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/> 
                      </Trigger> 
                      <Trigger Property="IsGrouping" Value="true"> 
                       <Setter Property="ScrollViewer.CanContentScroll" Value="false"/> 
                      </Trigger> 
                      <Trigger Property="IsEditable" 
                       Value="true"> 
                       <Setter Property="IsTabStop" Value="false"/> 
                       <Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Visible"/> 
                       <Setter TargetName="ContentSite" Property="Visibility" Value="Hidden"/> 
                      </Trigger> 
                     </ControlTemplate.Triggers> 
                    </ControlTemplate> 
                   </Setter.Value> 
                  </Setter> 
                  <Style.Triggers> 
                  </Style.Triggers> 
                 </Style> 

                 <!-- SimpleStyles: ComboBoxItem --> 
                 <Style x:Key="{x:Type ComboBoxItem}" TargetType="ComboBoxItem"> 
                  <Setter Property="SnapsToDevicePixels" Value="true"/> 
                  <Setter Property="OverridesDefaultStyle" Value="true"/> 
                  <Setter Property="Template"> 
                   <Setter.Value> 
                    <ControlTemplate TargetType="ComboBoxItem"> 
                     <Border Name="Border" SnapsToDevicePixels="true"> 
                      <ContentPresenter /> 
                     </Border> 
                     <ControlTemplate.Triggers> 
                      <Trigger Property="IsHighlighted" Value="true"> 
                       <Setter TargetName="Border" Property="Background" Value="{StaticResource SelectedBackgroundBrush}"/> 
                      </Trigger> 
                      <Trigger Property="IsEnabled" Value="false"> 
                       <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/> 
                      </Trigger> 
                      <Trigger Property="IsEnabled" Value="true"> 
                       <Setter Property="Foreground" Value="{StaticResource ActiveGlyphBrush}"/> 
                      </Trigger> 
                     </ControlTemplate.Triggers> 
                    </ControlTemplate> 
                   </Setter.Value> 
                  </Setter> 
                 </Style> 
                </ResourceDictionary> 

               </ResourceDictionary.MergedDictionaries> 
              </ResourceDictionary> 
             </Application.Resources> 
            </Application> 

Вот фактическое окно XAML:

<Window x:Class="WpfPropertyGrid_Demo.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:sys="clr-namespace:System;assembly=mscorlib" 
xmlns:wpg="clr-namespace:System.Windows.Controls" 
Title="WpfPropertyGrid Demo" mc:Ignorable="d" ResizeMode="CanResizeWithGrip" 
Width="360" Height="360" MinWidth="360" MinHeight="400"> 

<Window.Resources> 
    <ObjectDataProvider x:Key="SortTypes" MethodName="GetValues" ObjectType="{x:Type sys:Enum}"> 
     <ObjectDataProvider.MethodParameters> 
      <x:Type TypeName="wpg:PropertySort"/> 
     </ObjectDataProvider.MethodParameters> 
    </ObjectDataProvider> 
</Window.Resources> 

<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> 

    <StackPanel Orientation="Vertical" Margin="0,20,12,0" HorizontalAlignment="Right" VerticalAlignment="Top"> 
     <ComboBox Name="ComboSort" Margin="0,3,0,0" Width="95" FontSize="10" 
      SelectedIndex="0" ItemsSource="{Binding Source={StaticResource SortTypes}}" /> 
     <ComboBox Name="ComboSort2" Margin="0,3,0,0" Width="95" FontSize="10" 
      SelectedIndex="0" ItemsSource="{Binding Source={StaticResource SortTypes}}" /> 
    </StackPanel> 
</Grid> 

+1

Можете ли вы показать некоторые XAML? – Nitesh

+0

Извините, я проскользнул. Теперь приложение app.xaml находится в – VARAK

+0

. Это выглядит хорошо, потому что оно применяется к остальным элементам управления ComboBox, поэтому не думайте, имеет ли ControlTemplate какие-либо проблемы. Пожалуйста, покажите XAML, где вы создаете элементы управления ComboBox. – Nitesh

ответ

2

Пожалуйста, введите свои ComboBox стиль в отдельном ResourceDictionary, скажем ComboBox.xaml и объедините этот ComboBox.xaml в App.xaml.

<Application.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="ComboBox.xaml"/> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Application.Resources> 

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

Смежные вопросы