简体   繁体   中英

How to change background of listbox items (Textblock) in UWP

When trying to change background of TextBlock that is part of a DataTemplate of a ListBox the background is only around the text and not the entire block

In UWP TextBlock doesn't have background property so I've wrapped it in a border and changed the border's background like this:

<ListBox x:Name="BitsListView" ItemsSource="{x:Bind BitsList, Mode=TwoWay}" Loaded="BitsListView_Loaded"
    HorizontalAlignment="Left" IsEnabled="{x:Bind IsWriteAccess,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
    SelectionChanged="BitsListView_SelectionChanged " SelectionMode="Single">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border>
                <StackPanel Orientation="Horizontal">
                    <TextBlock x:Name="BitText" Text="{Binding}" Loaded="BitText_Loaded" />
                </StackPanel>
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>

And the color is changed in an OnLoaded event like this:

    private void BitText_Loaded(object sender, RoutedEventArgs e)
    {
        TextBlock bitText = sender as TextBlock;

        StackPanel sp = bitText.Parent as StackPanel;
        Border border = sp.Parent as Border;

        if ((int)bitText.DataContext == 1)
        {
            bitText.Foreground = new SolidColorBrush(Windows.UI.Colors.LightGreen);
            border.Background = new SolidColorBrush(Windows.UI.Colors.DarkGreen);

        }
        else
        {
            bitText.Foreground = new SolidColorBrush(Windows.UI.Colors.Gray);
            border.Background = new SolidColorBrush(Windows.UI.Colors.LightGray);
        }
    }

But the result is this: https://pasteboard.co/IlcZB1J.png

What i'm trying to achive is something like this: (Don't mind the bad MSPaint job)

https://pasteboard.co/Ild1plp.png

What i've tried to do to solve this is wrapping the stackpanel with border, but that didnt help. then i've tried to wrap the datatemplate but that is not possible, climbing further up the tree changing the backgrounds is not working properly, and obviously changing the ListBox's background paints the entire list, and I need only the blocks that has 1 to be painted fully and not just a little bit around the text

For your question, you do not need to use border to wrap the StackPanel, it will not work. You just need to define a style for ListBoxItem and apply it to ItemContainerStyle and set HorizontalContentAlignment=Stretch .

Here, I checked your code. I have some suggestions for you. In UWP, you could do most things with binding. That means you do not need to find the specific control and set its property value from DataTemplate in the page's code-behind. It's not best practice. Instead, you could define a custom class which includes three properties(text,background,foreground). Then, you could bind to these properties on your XAML page.

The complete code sample like the following:

<ListView x:Name="BitsListView" ItemsSource="{x:Bind BitsList, Mode=TwoWay}"
HorizontalAlignment="Left" SelectionMode="Single">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="VerticalContentAlignment" Value="Stretch"></Setter>
                <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
                <Setter Property="Padding" Value="0"></Setter>
            </Style>
        </ListView.ItemContainerStyle>
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" ></StackPanel>
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:Test">
                <StackPanel Background="{x:Bind backGround}">
                    <TextBlock x:Name="BitText" Text="{x:Bind content}" Foreground="{x:Bind foreGround}" HorizontalTextAlignment="Center"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
public class Test : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private int _content;

    public int content
    {
        get { return _content; }
        set
        {
            if (_content != value)
            {
                _content = value;
                if (value == 1)
                {
                    foreGround = new SolidColorBrush(Colors.LightGreen);
                    backGround = new SolidColorBrush(Colors.DarkGreen);
                }
                else
                {
                    foreGround = new SolidColorBrush(Colors.Gray);
                    backGround = new SolidColorBrush(Colors.LightGray);
                }
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("content"));
            }
        }
    }

    private SolidColorBrush _backGround;

    public SolidColorBrush backGround
    {
        get { return _backGround; }
        set
        {
            if (_backGround != value)
            {
                _backGround = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("backGround"));
            }
        }
    }

    private SolidColorBrush _foreGround;

    public SolidColorBrush foreGround
    {
        get { return _foreGround; }
        set
        {
            if (_foreGround != value)
            {
                _foreGround = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("foreGround"));
            }
        }
    }
}
public sealed partial class MainPage : Page
{
    private ObservableCollection<Test> BitsList { get; set; }

    public MainPage()
    {
        this.InitializeComponent();
        BitsList = new ObservableCollection<Test>();
        for (int i = 0; i < 10; i++)
        {
            Random random = new Random();
            BitsList.Add(new Test() { content = random.Next(0, 9) });
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM