< ListBox.Resources>中的ListBoxItem样式.还是在< ListBox.ItemContainerStyle>中? [英] ListBoxItem style in <ListBox.Resources> or in <ListBox.ItemContainerStyle>?

查看:348
本文介绍了< ListBox.Resources>中的ListBoxItem样式.还是在< ListBox.ItemContainerStyle>中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将ListBoxItem的xaml Style放在<ListBox.Resources><ListBox.ItemContainerStyle>中.查看代码.
问题是:有什么区别,我应该选择什么?

I can put a xaml Style for ListBoxItem in <ListBox.Resources> or in <ListBox.ItemContainerStyle>. See code.
Question is: what is the difference, what should I prefer?

<ListBox.Resources>
    <Style TargetType="ListBoxItem">
        <Setter Property="Canvas.Top" Value="{Binding Top}"/>
        <Setter Property="Canvas.Left" Value="{Binding Left}"/>
        <Setter Property="VerticalContentAlignment" Value="Stretch"/>
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="Padding" Value="0"/>
    </Style>
</ListBox.Resources>

OR:

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="Canvas.Top" Value="{Binding Top}"/>
        <Setter Property="Canvas.Left" Value="{Binding Left}"/>
        <Setter Property="VerticalContentAlignment" Value="Stretch"/>
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="Padding" Value="0"/>
    </Style>
</ListBox.ItemContainerStyle>

我接受一个答案,但是请注意并考虑一下这种奇怪的症状:
无论哪种方式,都给我这个奇怪的数据绑定警告:找不到引用为'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.ItemsControl',AncestorLevel ='1'的绑定源. BindingExpression:Path = Horizo​​ntalContentAlignment; DataItem = null ....等.
这是一个绑定,隐藏在系统Aero样式中的某个位置,不是我的.
仅当我同时使用两种样式时,此警告才会消失!

There is an answer that I accept, but behold and think about this strange symptom:
Either way gives me this strange databinding warning: Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null .... etc.
This is a binding that is hidden somewhere in the system Aero styles, it is not mine.
Only when I use both styles this warning disappears!

推荐答案

ItemContainerStyle是执行此操作的正确方法,因为它是显式设置的,因此wpf不必总是查找样式可能在的位置.它更快更好.这就是为什么存在该财产的原因.

ItemContainerStyle is the right way to do this because its set explicitly and so wpf will not need to look up always where the style might be. Its faster and better. That is why that property is there.

当未设置ItemContainerStyle时,WPF将在ListBox.ResourcesWindow.ResourcesApplication.Resources中寻找样式.这对性能不利.

When ItemContainerStyle is not set WPF will seek for the style in ListBox.Resources or Window.Resources or Application.Resources. That is bad for performance.

这篇关于&lt; ListBox.Resources&gt;中的ListBoxItem样式.还是在&lt; ListBox.ItemContainerStyle&gt;中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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