简体   繁体   English

为什么我的ListBoxItem样式会在更改内容时重置?

[英]Why my ListBoxItem style reset on changing content?

I have a listbox with 2 listbox items: 我有一个包含2个列表框项目的列表框:

<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: 当我在这样的代码中更改listboxitem内容时:

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

Style of my listboxitems resets - fontsizes, fontforeground, aligment - turn to default 我的列表框样式的样式重置-字体大小,fontforeground,适应性-转到默认值

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 . 由于您正在执行过程代码,因此很难不重复使用任何您容易拥有的样式,因此建议您阅读有关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. 之所以重置listbox项目的样式,是因为您要覆盖实际的ListBox项目,并为其分配一个仅string值,以便列表框的输出将仅包含不包含任何内容的string值然后将其转换为内部的普通Textblock控件。

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. 或者,您可以为listboxitem定义style ,然后将新的ListBoxItem的样式设置为新创建的样式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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