简体   繁体   中英

Why my ListBoxItem style reset on changing content?

I have a listbox with 2 listbox items:

<ListBox Name="Monday" HorizontalAlignment="Left" Height="65.125" Margin="78,45.625,0,0" VerticalAlignment="Top" Width="139" Style="{DynamicResource monday}" MouseUp="Monday_MouseUp">
    <ListBoxItem Name="MondayLB1" Content="24" HorizontalAlignment="Center" Margin="0,20,0,0" FontSize="20" Height="22" Foreground="White" Focusable="False">
    </ListBoxItem>
    <ListBoxItem Content="Февраль" HorizontalAlignment="Center" VerticalAlignment="Bottom" Foreground="White" Focusable="False">
    </ListBoxItem>
</ListBox>

When i change listboxitem content in code like this:

    listik[tmp].Items[0] = localDateTime.Day.ToString();

Style of my listboxitems resets - fontsizes, fontforeground, aligment - turn to default

What I must to do?

Since you are doing procedural code and it's so hard not to reuse any style that you have easily I suggest read more about DataBinding . But for the sake of your question, here's what's happening.

The reason why your style of your listbox items reset is because you are overriding the actual item which is the ListBox and assigning it with just a value of string so that output of the listbox will only have the string value which doesn't have anything in it which then just converts it into a normal Textblock control inside.

listik[tmp].Items[0] = localDateTime.Day.ToString();

Change it to like this

Monday.Items[0] = new ListBoxItem()
            {
                Content = localDateTime.Day.ToString(),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Bottom,
                Foreground = new SolidColorBrush(Colors.White),
                Height= 22,
                Focusable = false
            };

Or you can define a style for your listboxitem then set the new ListBoxItem's style to the newly created style.

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