【问题标题】:How to reset ListViewItem styles?如何重置 ListViewItem 样式?
【发布时间】:2012-09-13 10:01:54
【问题描述】:

我有一个这样定义的 xaml 样式:

<Style TargetType="{x:Type ListViewItem}">[...]</Style>

<Style TargetType="{x:Type ListViewItem}" x:Key="track_selected">[...]</Style>

这是以编程方式为列表视图项应用“track_selected”样式的代码

((ListViewItem)lv_tracklist.ItemContainerGenerator.ContainerFromIndex(currentTrackIndex)).Style = FindResource("track_selected") as Style;                

我的问题是,如何将 mylistview 中的所有 listviewitem 重置为其默认样式,即上面列出的第一个样式?

【问题讨论】:

  • 为什么要从后面的代码中设置样式?你考虑过使用触发器吗?它们的使用将解决您的问题
  • ((ListViewItem)lv_tracklist.ItemContainerGenerator.ContainerFromIndex(currentTrackIndex)).Style = null;
  • 谢谢科林史密斯。我是否必须为 (int i=lv_tracklist.Items.Count; --i >= 0;) {..} 循环所有 listviewItem 还是有更快的解决方案?
  • 对不起,但看起来更好这并不能解决我的问题,因为将样式设置为 null 不会恢复为默认样式,即 但它重置为默认的 wpf 样式 :-(

标签: c# wpf listview styles listviewitem


【解决方案1】:

虽然有例外,但不建议在代码后面操作 Views 对象。这应该在xaml 文件中完成。

这个例子在使用 WPF 时是不好的编码习惯

Styles 之间切换最好使用StyleSelectors。 在您的情况下,设置 ListView 的 ItemContainerStyleSelector 属性。

<Style x:Key="ItemStyle" TargetType="ListViewItem">
   <!-- Setters and Triggers -->
</Style>

<Style x:Key="TrackSelectedStyle" TargetType="ListViewItem">
   <!-- Setters and Triggers -->
</Style>

<example:TrackSelectionStyleSelectorx:Key="myContainerStyleSelector"
ItemsStyle ="{StaticResource ItemStyle}"
TrackSelectedStyle ="{StaticResource TrackSelectedStyle}"/>

<ListView ... ItemContainerStyleSelector="{StaticResource myContainerStyleSelector}"/>

还有StyleSelector 类(放在单独的.cs 文件中):

public class TrackSelectionStyleSelector: StyleSelector
{
   public Style ItemsStyle {get; set;}
   public Style TrackSelectedStyle {get; set;}

   public override Style SelectStyle( object item, DependencyObject container )
   {
     if ( /* isTrackSelected logic */ )
        return TrackSelectedStyle;

     return ItemsStyle;
   }

}

不要忘记将 item 参数转换为 ListViewItems 内容类型的类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多