ListView选择时使用不同的模板

时间:2016-09-24 20:51:15

标签: c# uwp

我正在尝试为列表视图项目选择时创建一个不同的模板,但是我无法找到任何关于这样做的模板。

根据是否选择了列表视图项目来选择模板的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

  

根据是否选择了列表视图项目来选择模板的最佳方法是什么?

更改默认模板并自定义VisualState内的动画是正确的方法。

  1. 在项目中复制并粘贴默认的ListViewItem样式和模板,请参阅here

  2. 更改SelectedPointerOverSelected视觉状态中的画笔:

  3. SystemControlHighlightListAccentLowBrush Selected视觉状态:

    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderBackground" Storyboard.TargetProperty="Fill">
             <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightListAccentLowBrush}" />
    </ObjectAnimationUsingKeyFrames>
    

    更改为:

    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderBackground" Storyboard.TargetProperty="Fill">
             <DiscreteObjectKeyFrame KeyTime="0" Value="Red" />
    </ObjectAnimationUsingKeyFrames>
    

    SystemControlHighlightListAccentMediumBrush PointerOverSelected视觉状态:

    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderBackground" Storyboard.TargetProperty="Fill">
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightListAccentMediumBrush}" />
    </ObjectAnimationUsingKeyFrames>
    

    更改为:

    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderBackground" Storyboard.TargetProperty="Fill">
            <DiscreteObjectKeyFrame KeyTime="0" Value="Red" />
    </ObjectAnimationUsingKeyFrames>
    

    <强>截图: enter image description here

    检查我已完成的样本here

    <强> -----更新(2016年9月27日)-----

      

    如何在选择ListBoxItem时使用它来更改ListBoxItem的DataTemplate

    如果您需要切换DataTemplate,可以从后面的代码更改它。

    1)在页面的资源中附加DataTeemplate:

    <Page.Resources>
      <DataTemplate x:Key="dataTemplate1">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="->" />
            <TextBlock Text="{Binding}" />
        </StackPanel>
      </DataTemplate>
    </Page.Resources>
    

    2)为SelectionChanged事件添加处理程序:

    <ListView SelectionChanged="ListView_SelectionChanged">
            <ListView.Items>
                <ListViewItem Content="One"></ListViewItem>
                <ListViewItem Content="Two"></ListViewItem>
                <ListViewItem Content="Three"></ListViewItem>
            </ListView.Items>
    </ListView>
    

    3)从后面的代码中更改DataTemplate

    private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //Assign DataTemplate for selected items
            foreach (var item in e.AddedItems)
            {
                ListViewItem _lvi = item as ListViewItem;
                _lvi.ContentTemplate = (DataTemplate)this.Resources["dataTemplate1"];
            }
            //Remove DataTemplate for unselected items
            foreach (var item in e.RemovedItems)
            {
                ListViewItem _lvi = item as ListViewItem;
                _lvi.ContentTemplate = null;
            }
        }
    

    enter image description here

    更新了我的演示:LINK