You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Xamarin.Forms与MAUI中用C#设置VisualState触发器

在C#中实现CollectionView选择状态的VisualState切换

核心思路

直接监听CollectionView.SelectionChanged事件,手动切换选中项与原选中项的VisualState,同时在C#代码中提前定义Normal和Selected两种状态的样式逻辑。


步骤1:在C#中定义VisualState及状态组

假设你的CollectionView项容器是ContentView(或其他继承自VisualElement的控件),可在页面初始化阶段创建状态组:

// 创建状态组
var commonStatesGroup = new VisualStateGroup { Name = "CommonStates" };

// 定义Normal状态样式
var normalState = new VisualState { Name = "Normal" };
normalState.Setters.Add(new Setter 
{ 
    Property = VisualElement.BackgroundColorProperty, 
    Value = Colors.Transparent 
});

// 定义Selected状态样式
var selectedState = new VisualState { Name = "Selected" };
selectedState.Setters.Add(new Setter 
{ 
    Property = VisualElement.BackgroundColorProperty, 
    Value = Colors.LightBlue 
});

// 将状态添加到组
commonStatesGroup.States.Add(normalState);
commonStatesGroup.States.Add(selectedState);

// 给CollectionView的项容器绑定状态组
var itemContainerStyle = new Style(typeof(ContentView))
{
    Setters =
    {
        new Setter
        {
            Property = VisualStateManager.VisualStateGroupsProperty,
            Value = new VisualStateGroupList { commonStatesGroup }
        }
    }
};

MyCollectionView.ItemContainerStyle = itemContainerStyle;

步骤2:监听SelectionChanged事件切换状态

在页面构造函数中绑定事件处理方法:

MyCollectionView.SelectionChanged += OnCollectionViewSelectionChanged;

实现事件逻辑,处理选中/取消选中的状态切换:

private void OnCollectionViewSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // 重置之前选中项的状态
    foreach (var prevItem in e.PreviousSelectedItems)
    {
        var itemContainer = MyCollectionView.ContainerForItem(prevItem) as VisualElement;
        if (itemContainer != null)
        {
            VisualStateManager.GoToState(itemContainer, "Normal");
        }
    }

    // 设置新选中项的状态
    foreach (var currItem in e.CurrentSelectedItems)
    {
        var itemContainer = MyCollectionView.ContainerForItem(currItem) as VisualElement;
        if (itemContainer != null)
        {
            VisualStateManager.GoToState(itemContainer, "Selected");
        }
    }
}

注意事项

  • 若ItemTemplate使用自定义根控件,需确保ContainerForItem能获取到对应的VisualElement对象。
  • 如需扩展状态样式(如字体颜色、边框),直接在VisualState的Setters中添加对应属性设置即可。
  • 多选模式下,上述代码会自动处理多个项的状态切换。

内容的提问来源于stack exchange,提问作者Alex Kay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 19:56:50