Настройка шаблона управления WPF ColorPicker

Я пытаюсь установить шаблон управления палитры цветов WPF в прямоугольник. Я хочу, чтобы вместо ColorPicker ComboBox отображалась только прямоугольная форма. Но когда я размещаю какой-либо элемент управления в ControlTemplate, я получаю сообщение об ошибке: «Ссылка на объект не установлена ​​​​на экземпляр объекта».

Это мой код wpf:

<wpfx:ColorPicker Name="ColorPicker1" Height="30" DisplayColorAndName="False"
                  Margin="29,72,366,209"
                  SelectedColorChanged="ColorPicker1_SelectedColorChanged">
    <wpfx:ColorPicker.Template>
        <ControlTemplate>
            <Rectangle ></Rectangle>
        </ControlTemplate>
    </wpfx:ColorPicker.Template>
</wpfx:ColorPicker>

Любые предложения о том, что я делаю неправильно?


person Irfan    schedule 10.08.2012    source источник
comment
Предполагаю, что вы используете: wpftoolkit.codeplex.com .... Вы пропустили закрывающий тег? ‹/wpfx:КолорПикер›   -  person Colin Smith    schedule 10.08.2012
comment
Нет.. Извините, я скопировал и вставил.. так что в реальном коде это не пропущено.   -  person Irfan    schedule 10.08.2012
comment
Не могли бы вы опубликовать трассировку стека полученного вами исключения?   -  person Captain O.    schedule 10.08.2012


Ответы (1)


Наиболее вероятная причина в том, что элемент управления ColorPicker ожидает какой-то элемент в своем шаблоне, обычно такие элементы имеют специальное имя, начинающееся с "PART_...". Я думаю, чтобы получить больше информации о том, какой элемент пропущен, вам нужно заглянуть в шаблон выбора цвета по умолчанию и узнать, какие элементы там и какие имена у них есть.

Возможный сценарий исправления: найдите имя элемента управления, которое является обязательным для элемента управления ColorPicker, и дайте это имя своему прямоугольнику.

Вот шаблон ColorPicker по умолчанию:

        <ControlTemplate TargetType="{x:Type local:ColorPicker}">
           <Grid>
              <ToggleButton x:Name="PART_ColorPickerToggleButton"
                            IsTabStop="True"
                            MinHeight="22" 
                            Background="{TemplateBinding Background}" 
                            BorderBrush="{TemplateBinding BorderBrush}" 
                            BorderThickness="{TemplateBinding BorderThickness}" 
                            VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                            HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                            Padding="{TemplateBinding Padding}"
                            IsChecked="{Binding IsOpen, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
                            IsHitTestVisible="{Binding IsOpen, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource InverseBoolConverter}}"
                            Style="{TemplateBinding ButtonStyle}">
                 <Grid Margin="2">
                    <Border x:Name="ColorOnly" Style="{StaticResource ColorDisplayStyle}" />

                    <Border x:Name="ColorAndName" Background="White" Visibility="Hidden">
                       <StackPanel Orientation="Horizontal">
                          <Border HorizontalAlignment="Left" Width="20" Margin="2,1,4,1" Style="{StaticResource ColorDisplayStyle}" BorderThickness="1" BorderBrush="#FFC9CACA" />
                          <TextBlock Text="{Binding SelectedColorText, RelativeSource={RelativeSource TemplatedParent}}" VerticalAlignment="Center" />
                       </StackPanel>
                    </Border>
                 </Grid>
              </ToggleButton>

              <Popup x:Name="PART_ColorPickerPalettePopup" VerticalAlignment="Bottom" IsOpen="{Binding ElementName=PART_ColorPickerToggleButton, Path=IsChecked}" StaysOpen="False" AllowsTransparency="True" Focusable="False" HorizontalOffset="1" VerticalOffset="1" PopupAnimation="Slide">
                 <Border BorderThickness="1" Background="{StaticResource PopupBackgroundBrush}" BorderBrush="{StaticResource ColorPickerDarkBorderBrush}" Padding="3">
                    <Grid>
                       <Grid.RowDefinitions>
                          <RowDefinition Height="Auto" />
                          <RowDefinition />
                          <RowDefinition Height="Auto" />
                       </Grid.RowDefinitions>

                       <Grid x:Name="_gridStandardColorsHost" Margin="4">
                          <Grid.RowDefinitions>
                             <RowDefinition Height="Auto" />
                             <RowDefinition Height="Auto" />
                             <RowDefinition Height="Auto" />
                             <RowDefinition Height="Auto" />
                          </Grid.RowDefinitions>

                          <!-- Available Colors -->
                          <Grid Grid.Row="1" Visibility="{TemplateBinding ShowAvailableColors, Converter={StaticResource BooleanToVisibilityConverter}}">
                             <Grid>
                                <Grid.RowDefinitions>
                                   <RowDefinition Height="Auto" />
                                   <RowDefinition />
                                </Grid.RowDefinitions>
                                <TextBlock Text="{TemplateBinding AvailableColorsHeader}" Background="AliceBlue" Padding="2" Margin="0,0,0,1" />
                                <ListBox x:Name="PART_AvailableColors"
                                         Grid.Row="1"
                                         ItemsSource="{Binding AvailableColors, RelativeSource={RelativeSource TemplatedParent}}"
                                         Style="{StaticResource ColorListStyle}" />
                             </Grid>
                          </Grid>

                          <!-- Standard Colors-->
                          <Grid Grid.Row="2" Visibility="{TemplateBinding ShowStandardColors, Converter={StaticResource BooleanToVisibilityConverter}}">
                             <Grid>
                                <Grid.RowDefinitions>
                                   <RowDefinition Height="Auto" />
                                   <RowDefinition Height="Auto" />
                                </Grid.RowDefinitions>
                                <TextBlock Text="{TemplateBinding StandardColorsHeader}" Background="AliceBlue" Padding="2" Margin="0,1,0,1" />
                                <ListBox x:Name="PART_StandardColors"
                                         Grid.Row="1"
                                         ItemsSource="{Binding StandardColors, RelativeSource={RelativeSource TemplatedParent}}"                                                      
                                         Style="{StaticResource ColorListStyle}" />
                             </Grid>
                          </Grid>

                          <!-- Recent Colors-->
                          <Grid Grid.Row="3" Margin="0,1,0,1" Visibility="{TemplateBinding ShowRecentColors, Converter={StaticResource BooleanToVisibilityConverter}}">
                             <Grid>
                                <Grid.RowDefinitions>
                                   <RowDefinition Height="Auto" />
                                   <RowDefinition Height="Auto" />
                                </Grid.RowDefinitions>
                                <TextBlock Text="{TemplateBinding RecentColorsHeader}" Background="AliceBlue" Padding="2" Margin="0,1,0,1" />
                                <ListBox x:Name="PART_RecentColors"
                                         Grid.Row="1"
                                         ItemsSource="{Binding RecentColors, RelativeSource={RelativeSource TemplatedParent}}"
                                         Style="{StaticResource ColorListStyle}" />
                             </Grid>
                          </Grid>
                       </Grid>

                       <!-- ColorCanvas -->
                       <Grid x:Name="_colorCanvasHost" Visibility="Collapsed">
                          <local:ColorCanvas x:Name="PART_ColorCanvas"
                                             Background="Transparent"
                                             BorderThickness="0"
                                             SelectedColor="{Binding SelectedColor, RelativeSource={RelativeSource TemplatedParent}}" />
                       </Grid>

                       <Separator Grid.Row="1" HorizontalAlignment="Stretch" Margin="5,0,5,0" />

                       <!-- More Colors Button -->
                       <ToggleButton x:Name="_colorMode" Grid.Row="2" Content="Advanced" Margin="5" Visibility="{TemplateBinding ShowAdvancedButton, Converter={StaticResource BooleanToVisibilityConverter}}" />
                    </Grid>
                 </Border>
              </Popup>
           </Grid>
           <ControlTemplate.Triggers>
              <Trigger Property="DisplayColorAndName" Value="True">
                 <Setter TargetName="ColorOnly" Property="Visibility" Value="Collapsed" />
                 <Setter TargetName="ColorAndName" Property="Visibility" Value="Visible" />
              </Trigger>
              <Trigger SourceName="_colorMode" Property="IsChecked" Value="True">
                 <Setter TargetName="_colorMode" Property="Content" Value="Standard" />
                 <Setter TargetName="_colorCanvasHost" Property="Visibility" Value="Visible" />
                 <Setter TargetName="_gridStandardColorsHost" Property="Visibility" Value="Collapsed" />
              </Trigger>
           </ControlTemplate.Triggers>
        </ControlTemplate>
person Captain O.    schedule 10.08.2012