gpt4 book ai didi

c# - 延迟取消选择 ListBoxItem

转载 作者:行者123 更新时间:2023-11-30 22:54:08 25 4
gpt4 key购买 nike

我想实现一种效果,其中 ListBoxItem 被选中(突出显示)几秒钟,然后被取消选中。尝试使用淡入淡出效果实现简单的控件突出显示,但为了使事情正常进行,我需要相应地更改一个属性。

我有一个 IsSelected 属性绑定(bind)到我的 View 模型属性:

<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Style>

我的属性(property)看起来是这样的:

public bool IsSelected
{
get => _isSelected;
set
{
// Update value
_isSelected = value;

// Raise property changed
OnPropertyChanged(nameof(IsSelected));
}
}

我试过使用延迟绑定(bind):

<ControlTemplate TargetType="{x:Type ListBoxItem}">
<ControlTemplate.Triggers>
<!-- Deselect after 5 seconds -->
<DataTrigger Binding="{Binding IsSelected, Delay=5000}" Value="True">
<Setter Property="IsSelected" Value="False" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>

我也尝试过使用 Storyboard:

<ControlTemplate TargetType="{x:Type ListBoxItem}">
<ControlTemplate.Triggers>
<!-- Deselect after 5 seconds -->
<DataTrigger Binding="{Binding IsSelected}" Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsSelected">
<DiscreteBooleanKeyFrame KeyTime="00:00:05" Value="False" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>

不幸的是,上述方法似乎都没有更新我的 IsSelected 属性并且 ListBoxItem 保持选中状态并突出显示。

我希望在 XAML(或扩展)、MVVM 风格、无代码隐藏和无浪费的计时器中完成此操作 - 这可能吗? 如果是这样,我如何正确取消选择延迟的 ListBoxItem

最佳答案

这是一个附加行为的例子,它或多或少应该做你想做的事:

public class DeselectBehavior
{
public static bool GetIsEnabled(ListBox listBox)
{
return (bool)listBox.GetValue(IsEnabledProperty);
}

public static void SetIsEnabled(ListBox listBox, bool value)
{
listBox.SetValue(IsEnabledProperty, value);
}

public static readonly DependencyProperty IsEnabledProperty =
DependencyProperty.RegisterAttached(
"IsEnabled",
typeof(bool),
typeof(DeselectBehavior),
new UIPropertyMetadata(false, OnChanged));

private static void OnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ListBox listBox = d as ListBox;
if((bool)e.NewValue)
{
listBox.AddHandler(ListBoxItem.SelectedEvent, (RoutedEventHandler)OnListBoxItemSelected, true);
}
else
{
listBox.RemoveHandler(ListBoxItem.SelectedEvent, (RoutedEventHandler)OnListBoxItemSelected);
}
}

private static async void OnListBoxItemSelected(object sender, RoutedEventArgs e)
{
await Task.Delay(2000);
ListBoxItem listBoxItem = e.OriginalSource as ListBoxItem;
if (listBoxItem != null)
listBoxItem.IsSelected = false;
}
}

XAML:

    <ListBox ... local:DeselectBehavior.IsEnabled="True">
...

关于c# - 延迟取消选择 ListBoxItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56560341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com