Элементы списка «Фокус и выделение» со множеством возможных шаблонов - PullRequest
1 голос
/ 28 октября 2010

Добрый день,

У меня есть список, который использует список элементов модели, адресов и адресов (унаследованных от адресов)

Теперь ранее я создавал шаблоны элементовв ItemContainerStyle, так что у меня есть только мои собственные визуальные эффекты фокусировки (т.е. нет пунктирной линии, нет светло-серого прямоугольника и т. д.).В прошлом это работало нормально.

Теперь мне нужны два шаблона, по одному для каждого типа (Address и RAddress).Я создал их в ListBox.resources как шаблоны по умолчанию (пример ниже):

<DataTemplate DataType="{x:Type DAL:RAddress}">

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

    <Style x:Key="AddressContainerStyle" TargetType="{x:Type ListBoxItem}">
        <Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
        <Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
        <Setter Property="Padding" Value="0,0,0,0"/>
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
    </Style>

Ранее, когдаШаблон был применен к стилю, это препятствовало отображению пунктирной линии и серого прямоугольника.Однако теперь они делают это, и настройки VisualState, которые я настроил, похоже, не применяются.

Пример всего DataTemplate следует:

<DataTemplate DataType="{x:Type DAL:Address}">
<Border x:Name="Bd" SnapsToDevicePixels="true" Background="#4C000000" CornerRadius="10" Padding="0" BorderBrush="#00FF0000" BorderThickness="1">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="SelectionStates">
            <VisualState x:Name="Unselected"/>
            <VisualState x:Name="Selected">
                <Storyboard>
                    <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                        <EasingColorKeyFrame KeyTime="0" Value="#80000000"/>
                    </ColorAnimationUsingKeyFrames>
                    <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                        <EasingColorKeyFrame KeyTime="0" Value="#00FF0000"/>
                    </ColorAnimationUsingKeyFrames>
                </Storyboard>
            </VisualState>
            <VisualState x:Name="SelectedUnfocused">
                <Storyboard>
                    <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                        <EasingColorKeyFrame KeyTime="0" Value="#80000000"/>
                    </ColorAnimationUsingKeyFrames>
                    <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                        <EasingColorKeyFrame KeyTime="0" Value="Red"/>
                    </ColorAnimationUsingKeyFrames>
                </Storyboard>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups> 
    <Grid Height="Auto" Width="Auto">
        <CheckBox x:Name="checkBox" Content="CheckBox" Margin="0" VerticalAlignment="Top" d:LayoutOverrides="Width" Style="{DynamicResource EditGemStyle}" HorizontalAlignment="Right" IsChecked="{Binding EditMode}"/>
        <StackPanel Margin="0" Orientation="Vertical" d:LayoutOverrides="Height">
            <Grid x:Name="DisplayGrid" Height="Auto" Width="Auto" d:LayoutOverrides="Width" VerticalAlignment="Stretch" Margin="7,3,11,3">
                <StackPanel Orientation="Vertical" Width="Auto" d:LayoutOverrides="Width, Height" Margin="0,0,10,0">
                    <TextBlock x:Name="AddressFriendlyName" TextWrapping="Wrap" Text="{Binding AddressFriendlyName}" FontSize="18.667" Style="{DynamicResource Data}"/>
                    <TextBlock x:Name="Address1" TextWrapping="Wrap" Text="{Binding Address1}" d:LayoutOverrides="Width" FontSize="13.333" Style="{DynamicResource Data}"/>
                    <TextBlock x:Name="Address2" TextWrapping="Wrap" Text="{Binding Address2}" FontSize="13.333" Style="{DynamicResource Data}"/>
                    <TextBlock x:Name="Address3" TextWrapping="Wrap" Text="{Binding Address3}" FontSize="13.333" Style="{DynamicResource Data}"/>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock x:Name="City" TextWrapping="Wrap" Text="{Binding City}" FontSize="13.333" Style="{DynamicResource Data}"/>
                        <TextBlock TextWrapping="Wrap" Text=", " FontSize="13.333" Style="{DynamicResource Data}"/>
                        <TextBlock x:Name="State" TextWrapping="Wrap" Text="{Binding State}" Margin="0,0,5,0" FontSize="13.333" Style="{DynamicResource Data}"/>
                        <TextBlock x:Name="ZIP" TextWrapping="Wrap" Text="{Binding ZIP}" FontSize="13.333" Style="{DynamicResource Data}"/>
                    </StackPanel>
                    <TextBlock x:Name="Country" TextWrapping="Wrap" Text="{Binding Country}" FontSize="13.333" Style="{DynamicResource Data}"/>
                </StackPanel>
            </Grid>
            <Grid x:Name="EditGrid" Height="Auto" Margin="7,3,11,0" Visibility="Collapsed">
                <StackPanel Orientation="Vertical" Width="Auto" Margin="0,0,10,0" d:LayoutOverrides="Width, Height">
                    <TextBox x:Name="AddressFriendlyName1" TextWrapping="Wrap" Text="{Binding AddressFriendlyName}" Template="{DynamicResource SnazzyTextBoxTemplate}" Margin="0,2" Foreground="White"/>
                    <TextBox x:Name="Address4" TextWrapping="Wrap" Text="{Binding Address1}" d:LayoutOverrides="Width" Template="{DynamicResource SnazzyTextBoxTemplate}" Margin="0,2" Foreground="White"/>
                    <TextBox x:Name="Address5" TextWrapping="Wrap" Text="{Binding Address2}" Template="{DynamicResource SnazzyTextBoxTemplate}" Margin="0,2" Foreground="White"/>
                    <TextBox x:Name="Address6" TextWrapping="Wrap" Text="{Binding Address3}" Template="{DynamicResource SnazzyTextBoxTemplate}" Margin="0,2" Foreground="White"/>
                    <StackPanel Orientation="Horizontal">
                        <TextBox x:Name="City1" TextWrapping="Wrap" Text="{Binding City}" Template="{DynamicResource SnazzyTextBoxTemplate}" Margin="0,2" Foreground="White"/>
                        <TextBlock TextWrapping="Wrap" Text=", " Foreground="White"/>
                        <TextBox x:Name="State1" TextWrapping="Wrap" Text="{Binding State}" Margin="0,2,5,2" Template="{DynamicResource SnazzyTextBoxTemplate}" Foreground="White"/>
                        <TextBox x:Name="ZIP1" TextWrapping="Wrap" Text="{Binding ZIP}" Template="{DynamicResource SnazzyTextBoxTemplate}" Margin="0,2" Foreground="White"/>
                    </StackPanel>
                    <TextBox x:Name="Country1" TextWrapping="Wrap" Text="{Binding Country}" Template="{DynamicResource SnazzyTextBoxTemplate}" Margin="0,2" Foreground="White"/>
                </StackPanel>
            </Grid>
        </StackPanel>
    </Grid>
</Border>
<DataTemplate.Triggers>
    <DataTrigger Binding="{Binding Address2}" Value="{x:Null}">
        <Setter TargetName="Address2" Property="Visibility" Value="Collapsed"/>
    </DataTrigger>
    <DataTrigger Binding="{Binding Address3}" Value="{x:Null}">
        <Setter TargetName="Address3" Property="Visibility" Value="Collapsed"/>
    </DataTrigger>
    <DataTrigger Binding="{Binding EditMode}" Value="False">
        <Setter Property="Visibility" TargetName="DisplayGrid" Value="Visible"/>
        <Setter Property="Visibility" TargetName="EditGrid" Value="Collapsed"/> 
    </DataTrigger>
    <DataTrigger Binding="{Binding EditMode}" Value="True">
        <Setter Property="Visibility" TargetName="DisplayGrid" Value="Collapsed"/>
        <Setter Property="Visibility" TargetName="EditGrid" Value="Visible"/> 
    </DataTrigger>
</DataTemplate.Triggers>

Ранее у меня былопопытался использовать StyleSelector для выбора между ItemContainerStyles, которые были созданы (по одному для каждого типа).Это привело к тому, что я столкнулся с ошибкой «не могу анимировать» (0). (1) «на неизменяемом экземпляре объекта», поэтому я начал смотреть на мою текущую настройку.

Как я могу применить свой собственный Фокус и Выбор?стилизация на двух отдельных шаблонах элементов, размещенных в одном и том же ListBox?

Любая помощь будет принята с благодарностью.

1 Ответ

1 голос
/ 02 ноября 2010

Я думаю, вам нужно переместить спецификацию раскадровок в ItemContainerStyle, а не указывать их в самих шаблонах данных. Это более СУХОЙ и приведет к меньшим осложнениям.

<Window.Resources>

    <DataTemplate DataType="{x:Type DAL:RAddress}">
        <TextBlock>RAddress!</TextBlock>
    </DataTemplate>

    <DataTemplate DataType="{x:Type DAL:Address}">
        <TextBlock>Address!</TextBlock>
    </DataTemplate>
    <Style x:Key="IHateDottedBorders" TargetType="{x:Type ListBoxItem}">
        <Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
        <Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
        <Setter Property="Padding" Value="0,0,0,0"/>
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <Border x:Name="Bd" SnapsToDevicePixels="true" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="SelectionStates">
                                <VisualState x:Name="Unselected"/>
                                <VisualState x:Name="Selected">
                                    <Storyboard>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                                            <EasingColorKeyFrame KeyTime="0" Value="#80000000"/>
                                        </ColorAnimationUsingKeyFrames>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                                            <EasingColorKeyFrame KeyTime="0" Value="#00FF0000"/>
                                        </ColorAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="SelectedUnfocused">
                                    <Storyboard>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                                            <EasingColorKeyFrame KeyTime="0" Value="#80000000"/>
                                        </ColorAnimationUsingKeyFrames>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Bd">
                                            <EasingColorKeyFrame KeyTime="0" Value="Red"/>
                                        </ColorAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="true">
                            <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
                        </Trigger>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsSelected" Value="true"/>
                                <Condition Property="Selector.IsSelectionActive" Value="false"/>
                            </MultiTrigger.Conditions>
                            <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
                        </MultiTrigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>


</Window.Resources>

<Grid>
    <ListBox ItemContainerStyle="{StaticResource IHateDottedBorders}" ItemsSource="{Binding CollectionOfAddresses}" />
</Grid>
...