WPF DataTrigger не запускается при применении стиля приложения? - PullRequest
0 голосов
/ 26 января 2010

Любая помощь по этой проблеме будет принята с благодарностью, так как я весь день искал ответы на вопросы, касающиеся этой области!

Я применил глобальный стиль к своему приложению WPF, добавив объединенный словарь в файл App.xaml. Это применило стиль к приложению, как и предполагалось, но есть ряд вещей, которые он сделал, которые я не до конца понимаю.

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

<StackPanel Margin="0,15,0,0" Width="auto" HorizontalAlignment="Left">
    <StackPanel.Resources>
        <converter:IntToBoolConverter x:Key="intToBoolConverter" />
        <converter:BoolToVisibilityConverter x:Key="boolToVisibilityConverter" />
    </StackPanel.Resources>
    <Label Content="Required Vehicles" HorizontalAlignment="Center" FontWeight="Bold" />
    <ListBox x:Name="lstVehicleRequests" ItemsSource="{Binding VehicleRequests}" Width="auto"
             IsSynchronizedWithCurrentItem="True">
        <ListBox.Resources>
            <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource BaseListBoxItem}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=RequestStatus.RequestStatusId}" Value="7">
                        <Setter Property="Background">
                            <Setter.Value>
                                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                    <GradientStop Color="#FFFFFFFB" Offset="0" />
                                    <GradientStop Color="IndianRed" Offset="0.5" />
                                    <GradientStop Color="#FFFFFFFB" Offset="1" />
                                </LinearGradientBrush>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ListBox.Resources>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid ShowGridLines="True">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="auto" />
                        <ColumnDefinition Width="auto" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="auto" />
                        <RowDefinition Height="4" />
                    </Grid.RowDefinitions>
                    <StackPanel Margin="0,8,0,0">
                        <TextBlock Margin="0,4,10,0" >
                        <Label Content="Coach Type" Width="120" />
                        <ComboBox ItemsSource="{Binding DataContext.CoachTypes, 
                                  RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
                                  SelectedItem="{Binding CoachType}" DisplayMemberPath="Name" Width="100" />
                        </TextBlock>
                        <TextBlock Margin="0,8,10,0">
                            <Label Content="No of Passengers" Width="120" />
                            <TextBox 
                                    keys:ValidKeys.Numeric="True"
                                    Validation.ErrorTemplate="{StaticResource validationTemplate}"
                                    Style="{StaticResource textBoxInError}" Width="50">
                                <TextBox.Text>
                                        <Binding Path="Passengers"
                                                  UpdateSourceTrigger="PropertyChanged">
                                            <Binding.ValidationRules>
                                                <val:RegularExpressionRule 
                                                    ErrorDescription="Please Enter a Numeric Size" 
                                                    RegularExpression="^\d*$" />
                                            </Binding.ValidationRules>
                                        </Binding>
                                    </TextBox.Text>
                            </TextBox>
                        </TextBlock>
                        <TextBlock Margin="0,8,10,0">
                            <Label Content="No of Drivers" Width="120" />
                            <TextBox
                                    keys:ValidKeys.Numeric="True"
                                    Validation.ErrorTemplate="{StaticResource validationTemplate}"
                                    Style="{StaticResource textBoxInError}" Width="50">
                                <TextBox.Text>
                                    <Binding Path="Drivers"
                                        UpdateSourceTrigger="PropertyChanged">
                                        <Binding.ValidationRules>
                                            <val:RegularExpressionRule 
                                                ErrorDescription="Please Enter a Numeric Size" 
                                                RegularExpression="^\d*$" />
                                            </Binding.ValidationRules>
                                        </Binding>
                                    </TextBox.Text>
                            </TextBox>
                        </TextBlock>
                        <TextBlock Margin="0,8,10,0">
                        <Label Content="Positioning Feeder Drivers" Width="120" />
                            <TextBox
                                    keys:ValidKeys.Numeric="True"
                                    Style="{StaticResource textBoxInError}" Width="50" MaxLength="3">
                                <TextBox.Text>
                                    <Binding Path="PositioningFeederDrivers"
                                        UpdateSourceTrigger="PropertyChanged">
                                        <Binding.ValidationRules>
                                            <val:RegularExpressionRule 
                                                ErrorDescription="Please Enter a Numeric Size" 
                                                RegularExpression="^\d*$" />
                                            </Binding.ValidationRules>
                                        </Binding>
                                    </TextBox.Text>
                            </TextBox>
                        </TextBlock>
                        <TextBlock Margin="0,8,10,0">                    
                        <Label Content="Wheelchair Access" Width="120" />
                        <ComboBox Width="100" SelectedIndex="{Binding WheelchairAccess, 
                                  Converter={StaticResource intToBoolConverter}}">
                            <ComboBoxItem Content="Not Required" />
                            <ComboBoxItem Content="Required" />
                        </ComboBox>
                        </TextBlock>
                        <TextBlock Margin="0,8,10,8">
                        <Label Content="Trailer" Width="120" />
                        <ComboBox Width="100" SelectedIndex="{Binding Trailer, 
                                  Converter={StaticResource intToBoolConverter}}">
                            <ComboBoxItem Content="Not Required" />
                            <ComboBoxItem Content="Required" />
                        </ComboBox>
                        </TextBlock>
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</StackPanel>

Затем я добавил свойство BasedOn, как вы можете видеть выше, почему я должен был сделать это, чтобы применить стиль к этому списку? Другие списки и другие элементы управления подобрали это автоматически?

В любом случае, вы увидите, что у меня есть блок данных с этим списком, который должен менять цвет фона, когда id состояния запроса = 7. Без свойства based на основе строка успешно меняет цвет на красный. Когда стиль применяется, он никогда не меняет цвет, и всегда применяется оранжевый цвет из шаблона.

HELP ?????

Очень ценится,

Mark

1 Ответ

0 голосов
/ 27 января 2010
<Style x:Key="BaseListBoxItem" d:IsControlPart="True" TargetType="{x:Type ListBoxItem}">
        <Setter Property="SnapsToDevicePixels" Value="true" />
        <Setter Property="OverridesDefaultStyle" Value="true" />
        <Setter Property="Padding" Value="3" />
        <Setter Property="Foreground" Value="{StaticResource OutsideFontColor}" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <ControlTemplate.Resources>
                        <Storyboard x:Key="HoverOn">
                            <DoubleAnimation Duration="00:00:00.1000000" Storyboard.TargetName="BackgroundGradientOver" 
                                             Storyboard.TargetProperty="Opacity" To="0.73" />
                        </Storyboard>
                        <Storyboard x:Key="HoverOff">
                            <DoubleAnimation Duration="00:00:00.4000000" Storyboard.TargetName="BackgroundGradientOver" 
                                             Storyboard.TargetProperty="Opacity" To="0" />
                        </Storyboard>
                        <Storyboard x:Key="SelectedOn">
                            <DoubleAnimation Duration="00:00:00.1000000" Storyboard.TargetName="BackgroundGradientSelected" 
                                             Storyboard.TargetProperty="Opacity" To="0.84" />
                            <DoubleAnimation Duration="00:00:00.1000000" Storyboard.TargetName="BackgroundGradientSelectedDisabled" 
                                             Storyboard.TargetProperty="Opacity" To="0.55" />
                        </Storyboard>
                        <Storyboard x:Key="SelectedOff">
                            <DoubleAnimation Duration="00:00:00.4000000" Storyboard.TargetName="BackgroundGradientSelected" 
                                             Storyboard.TargetProperty="Opacity" To="0" />
                            <DoubleAnimation Duration="00:00:00.4000000" Storyboard.TargetName="BackgroundGradientSelectedDisabled" 
                                             Storyboard.TargetProperty="Opacity" To="0" />
                        </Storyboard>
                    </ControlTemplate.Resources>
                    <Grid SnapsToDevicePixels="true">
                        <Rectangle x:Name="BackgroundGradientOver" RadiusX="1" RadiusY="1" Stroke="{DynamicResource MouseOverBorderBrush}" 
                                   Opacity="0" Fill="{DynamicResource MouseOverBrush}"/>
                        <Rectangle x:Name="BackgroundGradientSelectedDisabled" RadiusX="1" RadiusY="1" Opacity="0" Fill="{DynamicResource 
                            ListItemSelectedBrush}" Stroke="{DynamicResource ListItemSelectedBorderBrush}"/>
                        <Rectangle x:Name="BackgroundGradientSelected" Stroke="{DynamicResource PressedBorderBrush}" StrokeThickness="1" 
                                   RadiusX="1" RadiusY="1" Opacity="0" Fill="{DynamicResource PressedBrush}">

                        </Rectangle>
                        <ContentPresenter x:Name="contentPresenter" Content="{TemplateBinding Content}" Margin="{TemplateBinding Padding}"
                                          ContentTemplate="{TemplateBinding ContentTemplate}" 
                                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"  />
                    </Grid>
                    <ControlTemplate.Triggers>

                        <Trigger Property="IsSelected" Value="true">
                            <Trigger.ExitActions>
                                <BeginStoryboard Storyboard="{StaticResource SelectedOff}" x:Name="SelectedOff_BeginStoryboard" />
                            </Trigger.ExitActions>
                            <Trigger.EnterActions>
                                <BeginStoryboard Storyboard="{StaticResource SelectedOn}" x:Name="SelectedOn_BeginStoryboard" />
                            </Trigger.EnterActions>

                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Trigger.ExitActions>
                                <BeginStoryboard Storyboard="{StaticResource HoverOff}" x:Name="HoverOff_BeginStoryboard" />
                            </Trigger.ExitActions>
                            <Trigger.EnterActions>
                                <BeginStoryboard Storyboard="{StaticResource HoverOn}" />
                            </Trigger.EnterActions>
                        </Trigger>

                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="{DynamicResource DisabledForegroundBrush}" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
...