2015-11-02 117 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>