【发布时间】:2020-05-08 13:07:03
【问题描述】:
我有一个场景,两个列表将显示在一个窗口中,但用户只能选择列表中的任何一个并继续。
如果用户在 listbox1 中选择一个项目并再次从 listbox2 中选择,则假设 listbox1 和 listbox2 应该删除 listbox1 中的选定项目。
我只能通过 xaml 而不是代码隐藏来实现这一点。所以我在下面尝试:
<Grid.Resources>
<Storyboard x:Key="temp" >
<Int32Animation Storyboard.TargetName="lstbox" Storyboard.TargetProperty="(ListBox.SelectedIndex)"
To="-1" Duration="0:0:.2" />
</Storyboard>
<Storyboard x:Key="temp1" >
<Int32Animation Storyboard.TargetName="listBox1" Storyboard.TargetProperty="(ListBox.SelectedIndex)"
To="-1" Duration="0:0:.2" />
</Storyboard>
</Grid.Resources>
如上所述,创建了两个故事板,将 selectedIndex 设置为 -1,并在选择更改事件触发器时调用该故事板,如下所示:
<ListBox Name="listBox1" HorizontalAlignment="Left" Grid.Column="1">
<ListBox.Triggers>
<EventTrigger RoutedEvent="ListBox.SelectionChanged">
<BeginStoryboard Storyboard="{StaticResource temp}"/>
</EventTrigger>
</ListBox.Triggers>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Background" Value="AliceBlue" />
<Setter Property="BorderBrush" Value="BlanchedAlmond" />
<Setter Property="BorderThickness" Value="2" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
<ListBoxItem Content="Coffie"></ListBoxItem>
<ListBoxItem Content="Tea"></ListBoxItem>
<ListBoxItem Content="Orange Juice"></ListBoxItem>
<ListBoxItem Content="Milk"></ListBoxItem>
<ListBoxItem Content="Iced Tea"></ListBoxItem>
<ListBoxItem Content="Mango Shake"></ListBoxItem>
</ListBox>
<ListBox Name="lstbox" ItemsSource="{Binding MyData}" Grid.Column="1" Grid.Row="1" SelectionChanged="lstbox_SelectionChanged">
<ListBox.Triggers>
<EventTrigger RoutedEvent="ListBox.SelectionChanged">
<BeginStoryboard Storyboard="{StaticResource temp1}"/>
</EventTrigger>
</ListBox.Triggers>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Background" Value="AliceBlue" />
<Setter Property="BorderBrush" Value="BlanchedAlmond" />
<Setter Property="BorderThickness" Value="2" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="DarkViolet" />
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
当我将 SelectedIndex 设置为 -1 时,通过后面的代码来清除 selectedItem 的样式,但通过情节提要并没有清除样式。
请告诉我任何其他方式或指导我使其工作。
我只能通过xaml来实现。
谢谢,
纳加斯里。
【问题讨论】:
-
这应该在视图模型中处理,当然不在标记中...
-
我们的项目动态设置viewmodel。所以我在实施时无法决定
-
那么你不使用 MVVM 吗?因为那时您肯定会在具有 ListBox 元素的视图的视图模型中实现这一点。为什么还要在 XAML 中实现这种逻辑?
-
我已经使用附加行为实现了它,我不知道为什么对这个问题持否定态度。无论如何感谢大家的投入