【问题标题】:UWP: changing the (text) style of a ListBoxItem Element in c# codeUWP:在 c# 代码中更改 ListBoxItem 元素的(文本)样式
【发布时间】:2015-09-24 15:24:23
【问题描述】:

我有一个列表框,里面有很多列表框项。这些项目仅包含文本元素。 我想要做的是更改 c# 代码中单个列表框项的文本样式(可能还有背景颜色)(因为我需要应用条件)。我该怎么办?

XAML:

<ListBox x:Name="todoList" Margin="5, 5, 5, 5" Grid.Row="1" SelectionChanged="todoList_SelectionChanged"/>

我通过解析文件然后将项目添加到列表框来填充列表框。

在我的情况下,对 ItemControlStyleSelector 进行子类化似乎不起作用,因为您无法在 UWP 情况下覆盖 SelectStyle 函数。

我可以通过以下方式将样式应用于整个 ListBox(所有 ListBoxItems):

Style st = new Style();
st.TargetType = typeof(ListBoxItem);
st.Setters.Add(new Setter(ListBoxItem.BackgroundProperty, "Blue"));
todoList.ItemContainerStyle = st;

在代码中只更改一个项目的样式是什么好方法?目标是在用户按下键盘上的特定按钮/键后对某些项目应用一些样式。

谢谢!

【问题讨论】:

    标签: c# .net listbox listboxitem uwp


    【解决方案1】:

    ListBox 不提供内置支持来更改特定 ListBoxItem 的样式。

    解决方法是使用 VisualTreeHelper:

    XAML:

        <ListBox x:Name="todoList">
            <ListBoxItem>Item#1</ListBoxItem>
            <ListBoxItem>Item#2</ListBoxItem>
            <ListBoxItem>Item#3</ListBoxItem>
            <ListBoxItem>Item#4</ListBoxItem>
            <ListBoxItem>Item#5</ListBoxItem>
        </ListBox>
    

    C#:

    public void OnClick(Object sender, RoutedEventArgs e)
    {
        var results = new List<ListBoxItem>();
    
        FindChildren(results, todoList);
    
        results[2].Background = new SolidColorBrush(Color.FromArgb(120, 0, 0, 255));
    }
    
    internal static void FindChildren<T>(List<T> results, DependencyObject startNode) where T : DependencyObject
    {
        int count = VisualTreeHelper.GetChildrenCount(startNode);
    
        for (int i = 0; i < count; i++)
        {
            DependencyObject current = VisualTreeHelper.GetChild(startNode, i);
            if ((current.GetType()).Equals(typeof(T)) || (current.GetType().GetTypeInfo().IsSubclassOf(typeof(T))))
            {
                T asType = (T)current;
                results.Add(asType);
            }
    
            FindChildren<T>(results, current);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多