2015-11-12 76 views
2

我正在用列表视图编写UWP应用程序。 listviewitems包含一个文本块和一个复选框。当选择listviewitem时,我希望复选框检查/取消选中。我还想删除“selected”动画,其中listviewitem在选中时变成蓝色。当在列表视图中选择项目时勾选复选框UWP

我发现不同的解决方案,但他们似乎都依赖于使用触发器,Visual Studio告诉我在UWP中不可用。

我该如何解决这个问题,在UWP中没有触发器?

我的列表视图:

<ListView Name="ListViewItems" Grid.Row="2"> 
     <ListView.ItemContainerStyle> 
      <Style TargetType="ListViewItem"> 
       <Setter Property="Margin" Value="0,0,0,1"></Setter> 
       <Setter Property="Background" Value="White"></Setter> 
       <Setter Property="Padding" Value="5"></Setter> 
      </Style> 
     </ListView.ItemContainerStyle> 
     <ListView.ItemTemplate> 
      <DataTemplate> 
       <Grid Padding="5,0"> 
        <CheckBox HorizontalAlignment="Right" VerticalAlignment="Center" Name="CheckBoxItem"></CheckBox> 
        <TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" Name="TextblockItem" Text="{Binding}"></TextBlock> 
       </Grid> 
      </DataTemplate> 
     </ListView.ItemTemplate> 
    </ListView> 

回答

0

如果该ListViewItemSource势必对一个视图模型集合,我建议你添加一个bool到项目类的集合。

因此,例如,如果您正在显示人员,请将Person bool IsSelected字段添加到Person类。 然后,您可以使用此字段将其绑定到IsChecked道具视图中的复选框,只需要做的事情是一定要设置模式=双向

最后一件事剩下要做的就是切换此IsSelected领域,您可以通过将ListView的SelectedItem绑定到ViewModel上的Person属性,并在每次调用该属性时(setter属性),切换给定的IsSelected字段。

当选择了ListView的项目要覆盖在颜色的变化,你需要在选择的ListViewItem得到ListView控件模板的复制和删除颜色设置处于选中状态

+0

我有一些类似的问题,您的解决方案帮助了我很多,感谢 – Maryam

+0

我觉得像加选择布尔到模型休息MVVM。 – Ryan

1

,我希望复选框检查/取消选中。

可以将财产器isChecked直接结合的复选框ListViewItem的IsSelected属性:

<CheckBox 
     HorizontalAlignment="Right" 
     Margin="10" 
     VerticalAlignment="Center" 
     IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}}" 
     Name="CheckBoxItem"> 
</CheckBox> 

每当ListViewItem的变化IsSelected属性,该复选框将被选中/取消。

我还想删除“selected”动画,其中 listviewitem在选中时变为蓝色。

下面的代码可以帮助您实现这一点,但是,它会覆盖项目的模板,这意味着您必须编写自己的模板。

  <Style TargetType="{x:Type ListViewItem}"> 
       <Setter Property="FocusVisualStyle" Value="{x:Null}" />      
       <Setter Property="Template"> 
        <Setter.Value> 
         <ControlTemplate TargetType="{x:Type ListViewItem}"> 
          <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
               VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
               SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" /> 
         </ControlTemplate> 
        </Setter.Value> 
       </Setter> 
      </Style> 
+0

看起来像一个干净的解决方案,但你有没有尝试使绑定​​到IsChecked属性?我读[这里](http://stackoverflow.com/questions/15233072/windowsphone-relativesource-mode-findancestor-ancestortype-cannotresolve-sy)AncestorType在Windows Phone上不受支持,我似乎无法做到它也在UWP中工作。 “AncestorType不是regicnized或不可访问的”。 – Masterchief

+0

因为在Windows Phone(我测试一个绑定,但在桌面应用程序)上不可能这样做,所以您可以尝试Depechie的解决方案,但要小心,这样做可以混合使用业务逻辑和UI,因为您正在创建一个属性只是为了处理一些UI逻辑,我建议你为绑定到列表的项目创建一个Viewmodel。 –

+0

如果你仍然需要抓住所选的那个,如果你离开并回到页面,则取决于一点。然后让属性绑定到你的viewmodel中的对象有助于:) – Depechie

相关问题