2015-11-02 55 views
0

我有一个ListView,每个项目都有一个切换按钮。我希望能够在从列表中选择项目时切换按钮,并且在取消选择项目时松开。它必须遵循mvvm,所以没有代码隐藏。制作项目选择的ToggleButtons ListView

这里是我的设置:

  <ListView x:Name="stampList" 
        ItemsSource="{Binding AllStampImages}"> 

       <ListView.ItemTemplate>    
        <DataTemplate> 

         <StackPanel Orientation="Vertical" Margin="0,2,0,0"> 
          <ToggleButton Width="72" 
             Height="72" 
             Command="{Binding StampSelectedCommand}"/> 
         </StackPanel> 

        </DataTemplate> 
       </ListView.ItemTemplate> 
      </ListView> 

我的问题是,当我打的切换按钮没有选择的项目。同样,当我在切换按钮之外(仍在listView项目的边界内)时,该项目被选中,但按钮未被切换。

如何将两者结合在一起?

enter image description here

回答

1

做最彻底的方法是,使视图模型或模型层提供的项目的集合。

  1. 每个项目应该有一个IsSelected布尔属性:
class LineItem 
{ 
    private bool isSelected; 
    public bool IsSelected 
    { 
     get { return isSelected; } 
     set { isSelected = value; } 
    } 
    private String label; 
    public String Label 
    { 
     get { return label; } 
     set { label = value; } 
    } 
} 
  • 应该有一些结合到模型IsSelected属性:
  • 2.1在ListView.ItemTemplate上

    <ListView x:Name="list1" SelectionMode="Multiple" ItemContainerStyle="{DynamicResource ListViewItemStyle1}" Margin="0,0,334,0"> 
        <ListView.ItemTemplate> 
         <DataTemplate> 
          <ToggleButton Margin="5" Content="{Binding Label}" IsChecked="{Binding IsSelected}"/> 
         </DataTemplate> 
        </ListView.ItemTemplate> 
    

    2.2在ListViewItem的模板

    创建的列表视图中右键单击模板,

    在菜单:“编辑其他模板/编辑生成的项容器(空)。

    装满下面的代码:”

    <Style x:Key="ListViewItemStyle1" TargetType="{x:Type ListViewItem}"> 
         <Setter Property="IsSelected" Value="{Binding IsSelected}"/> 
         <Setter Property="Template"> 
          <Setter.Value> 
           <ControlTemplate TargetType="{x:Type ListViewItem}"> 
            <Grid x:Name="Bd"> 
             <ContentPresenter /> 
            </Grid> 
            <ControlTemplate.Triggers> 
             <MultiTrigger> 
              <MultiTrigger.Conditions> 
               <Condition Property="IsSelected" Value="True"/> 
              </MultiTrigger.Conditions> 
              <Setter Property="Background" TargetName="Bd" Value="#FF204080"/> 
             </MultiTrigger> 
            </ControlTemplate.Triggers> 
           </ControlTemplate> 
          </Setter.Value> 
         </Setter> 
        </Style> 
    

    触发基于模型的IsSelected属性
    网格被命名为屋宇署,以改变其在触发后台

    链接到。完整的工作演示:http://1drv.ms/1iyvPgt

    注意

    我想要回答这个问题。 但在我的愚见,我不会使用ListView可能是你有很好的理由,我gnore。

    我更喜欢使用ItemsControl,它是一个不允许进行选择的列表框。

    我会把切换按钮,自定义模板,如果需要,把蓝色背景。
    它会删除所有触发东西 ,...

    最佳编码

    2

    您可能需要您custome属性为Selector.IsSelected属性绑定。在这种情况下,您的属性切换按钮。

    试着这么做:

     <ListView.ItemContainerStyle> 
          <Style TargetType="{x:Type TreeViewItem}"> 
           <Setter Property="Selector.IsSelected" Value="{Binding [Value of your toggle button], Mode=TwoWay}" /> 
          </Style> 
         </ListView.ItemContainerStyle>