Случайно выбранный элемент при использовании Trigger для изменения DataTemplate - PullRequest
0 голосов
/ 26 января 2019

Я пытаюсь изменить свой ContentTemplate, используя этот код:

<DataTemplate x:Key="SidebarItemStyle" DataType="{x:Type domain:SidebarDataTemplate}">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Rectangle Grid.Row="0" Grid.RowSpan="2" Fill="{StaticResource BluePrimaryBrush}" />
        <Image Grid.Row="0" Style="{StaticResource SidebarMenuImageSyle}" Source="{Binding Image}" />
        <TextBlock Grid.Row="1" Style="{StaticResource SidebarMenuTextStyle}" Text="{Binding Title}" />
    </Grid>
    </DataTemplate>
<DataTemplate x:Key="SidebarSelectedItemStyle" DataType="{x:Type domain:SidebarDataTemplate}">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
            <RowDefinition/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Rectangle Grid.Row="0" Grid.RowSpan="2" Fill="{StaticResource BluePrimaryBrush}" />
        <Rectangle Grid.Row="0" Grid.RowSpan="2" Fill="{StaticResource TransparentOverlay1Brush}" />
        <Image Grid.Row="0" Style="{StaticResource SidebarMenuImageSyle}" Source="{Binding SelectedImage}" />
        <TextBlock Grid.Row="1" Style="{StaticResource SidebarMenuTextStyle}" Text="{Binding Title}" />
    </Grid>
</DataTemplate>

<Style TargetType="{x:Type ListBoxItem}" x:Key="SidebarContainerStyle">
    <Setter Property="ContentTemplate" Value="{StaticResource SidebarItemStyle}" />
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="ContentTemplate" Value="{StaticResource SidebarSelectedItemStyle}" />
        </Trigger>
    </Style.Triggers>
</Style>

Но, когда я нажимаю на элемент, он продолжает выбирать случайный элемент или только первый элемент.Суть в том, что я хочу использовать разные Image и добавить наложение к выбранному элементу.

Random click

Ответы [ 2 ]

0 голосов
/ 27 января 2019

Оказывается, это странное поведение вызвано DragMoveBehavior из этого поста .

public class DragMoveBehavior : Behavior<Window>
{
    protected override void OnAttached()
    {
        AssociatedObject.MouseMove += AssociatedObject_MouseMove;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.MouseMove -= AssociatedObject_MouseMove;
    }

    private void AssociatedObject_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed && sender is Window window)
        {
            // In maximum window state case, window will return normal state and
            // continue moving follow cursor
            if (window.WindowState == WindowState.Maximized)
            {
                window.WindowState = WindowState.Normal;

                // 3 or any where you want to set window location after
                // return from maximum state
                Application.Current.MainWindow.Top = 3;
            }

            window.DragMove();
        }
    }
}

Окно XAML:

<Window ...
        xmlns:h="clr-namespace:A.Namespace.Of.DragMoveBehavior"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
    <i:Interaction.Behaviors>
        <h:DragMoveBehavior />
    </i:Interaction.Behaviors>
    ...
</Window>

Удаляя поведениеиз окна исчезла эта странная проблема случайного щелчка.Спасибо redcurry за ответ, я также использовал ваш код в своем приложении.

ОБНОВЛЕНИЕ

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

0 голосов
/ 26 января 2019

Я не уверен, что происходит в вашем случае, но немного подозрительно, что ваш ContentTemplate никогда не определяет ContentPresenter. Во всяком случае, я думаю, что есть другой способ достичь вашей цели. Попробуйте следующий XAML:

<ListBox ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Rectangle Grid.Row="0" Grid.RowSpan="2" Fill="{StaticResource BluePrimaryBrush}" />
                <Rectangle Grid.Row="0" Grid.RowSpan="2" Fill="{StaticResource TransparentOverlay1Brush}">
                    <Rectangle.Style>
                        <Style TargetType="Rectangle">
                            <!-- Don't show overlay when not selected -->
                            <Setter Property="Visibility" Value="Collapsed" />
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType=ListBoxItem}}" Value="True">
                                    <!-- Show overlay when selected -->
                                    <Setter Property="Visibility" Value="Visible" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </Rectangle.Style>
                </Rectangle>
                <Image Grid.Row="0">
                    <Image.Style>
                        <Style TargetType="Image">
                            <!-- Use Image when not selected -->
                            <Setter Property="Source" Value="{Binding Image}" />
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType=ListBoxItem}}" Value="True">
                                    <!-- Use SelectedImage when selected -->
                                    <Setter Property="Source" Value="{Binding SelectedImage}" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </Image.Style>
                </Image>
                <TextBlock Grid.Row="1" Text="{Binding Title}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>

    <!-- Remove default selection highlighting -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <ContentPresenter />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Вы определяете ItemTemplate, и в зависимости от того, выбран ли ListBoxItem, в котором он находится, вы выбираете, использовать ли оверлей и свойство SelectedImage. ListBoxItem.ControlTemplate заменяется пустым ContentPresenter, чтобы удалить все выделения по умолчанию (поскольку вы делаете это самостоятельно).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...