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

UWP ListView右键无法将TextBlock前景色设为黑色 左键功能正常如何解决?

问题原因分析
  • 事件源获取逻辑不可靠:左键点击你用的是ItemClick路由事件,参数e.ClickedItem直接返回条目绑定的数据源,逻辑稳定。但右键点击你用的是RightTapped路由事件,直接把e.OriginalSource强转成ListViewItemPresenter是不可靠的——如果点击位置落在条目内部的子元素(比如你要修改的TextBlock本身),as转换会返回null,后续拿DataContext、查找ListViewItem的逻辑都会全部失效,自然不会执行样式修改。
  • 背景色设置冲突:你在右键事件里同时把Background和Foreground都设为了黑色,就算前景色设置生效,文字和背景同色也看不到显示效果,会误以为前景色设置失败,这行背景色设置是多余的错误代码。
  • 默认样式覆盖:ListView自带的条目选中、指针悬停状态的样式优先级高于你手动设置的Foreground属性,会把你的修改直接覆盖。
修复方案

修改后的RightTapped事件代码如下:

private void SelectList1_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
    // 从事件源向上遍历视觉树查找对应的ListViewItem,兼容点击任意子元素的场景
    DependencyObject depObj = e.OriginalSource as DependencyObject;
    while (depObj != null && depObj is not ListViewItem)
    {
        depObj = VisualTreeHelper.GetParent(depObj);
    }
    if (depObj is not ListViewItem item) return;

    Article selectArticle = item.Content as Article;
    if (selectArticle == null) return;

    // 仅修改前景色,删除错误的黑色背景设置
    item.Foreground = new SolidColorBrush(Colors.Black);
    // 可选:取消条目选中状态,避免默认选中样式覆盖自定义前景色
    item.IsSelected = false;

    DataAccess.ArticleNotRead(selectArticle.article_id);
    // 标记事件已处理,防止冒泡触发其他默认行为
    e.Handled = true;
}

如果修改ListViewItem.Foreground仍然被默认样式覆盖,可以直接获取条目模板内的TextBlock实例修改属性,优先级更高:

// 需将代码中ItemText替换为你DataTemplate内TextBlock的x:Name属性值
TextBlock itemText = item.FindName("ItemText") as TextBlock;
if (itemText != null)
{
    itemText.Foreground = new SolidColorBrush(Colors.Black);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:24:04