UWP:在C#代码中更改ListBoxItem元素的(文本)样式 [英] UWP: changing the (text) style of a ListBoxItem Element in c# code

查看:416
本文介绍了UWP:在C#代码中更改ListBoxItem元素的(文本)样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a listbox with many listboxitems inside. those items only contain text elements. What I want to do is change the text style (and maybe the background colour as well) for a single listboxitem in c# code (as I need to apply conditions). how would I go about that?

XAML:

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

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

I fill the listbox by parsing a file and then adding items to the listbox.

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

Subclassing the ItemControlStyleSelector did not seem to work in my case as you cannot overwrite the SelectStyle function in the UWP case.

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

I am able to apply a style to the WHOLE ListBox (all ListBoxItems) by:

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

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

What would a good approach be to change only one item's style in code? The goal is to apply some styling to certain items after the user pressed a specific button / key on the keyboard.

谢谢!

推荐答案

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

The ListBox does not provide the build-in support to change the style of a specific ListBoxItem.

解决方法是使用VisualTreeHelper:

The workaround is using 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);
    }
}

这篇关于UWP:在C#代码中更改ListBoxItem元素的(文本)样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆