2013-10-02 34 views
0

我有被傳遞到一個頁面一個IEnumerable,我想告訴我的網頁上這份名單,我可以簡單地設置一個列表框,以它的的ItemsSource和字符串列表會顯示如何寫一個ItemsControl的項目模板

但我想提出一個複選框,每個項目旁,使串可選擇與複選框(怎麼樣,你在android系統將聯繫人添加到SMS)。我可以放置兩個列表框並將它們的滾動對象綁定,然後將其中一個的ItemsSource設置爲IEnumerable,並將複選框添加到第二個列表框foreach項目。但它很尷尬!

現在,首先它控制的是這個任務的ItemsControl或列表框(我知道列表框是一個ItemsControl)更好嗎? 然後我該如何編寫listbox/Itemscontrol項目的這種模板?

我扔搜索互聯網和所有我發現用的DataTemplates例子!但我沒有任何數據綁定!我將一個IEnumerable傳遞給一個Page,然後我將Listbox/ItemsControl的Itemssource設置爲它。我期望ItemsControl/Listbox將複選框放在每個項目旁邊。

回答

1

HierarchicalDataTemplate可能是你的答案。

我寫了只有一個Menu裏面一個用戶控件。爲了模板/樣式MenuItens將在運行時插入,我使用HierarchicalDataTemplate如上所述。

因此,在我的<UserControl.Resources>標籤內插入了下面的代碼。請注意,代碼只是您實際能做的一個小型預覽! (WPF是非常定製!)
代碼:

<HierarchicalDataTemplate DataType="{x:Type ViewModel:CmpMenuViewModel}" ItemsSource="{Binding MenuSubItem}" > 
     <HierarchicalDataTemplate.ItemContainerStyle> 
      <Style TargetType="MenuItem"> 
       <Setter Property="Command" Value="{Binding Comando}" /> 
       <Setter Property="CommandParameter" Value="{Binding Texto}"/> 
      </Style> 
     </HierarchicalDataTemplate.ItemContainerStyle> 
     <StackPanel Orientation="Horizontal"> 
      <Image Source="{Binding Imagem}" /> 
      <AccessText Text="{Binding Texto}" /> 
     </StackPanel> 
</HierarchicalDataTemplate> 

<StackPanel...位是我實際的模板。
我的風格位於<HierarchicalDataTemplate.ItemContainerStyle>之內。不要忘了將<Style TargetType=>更改爲您的實際TargetType!

此致敬禮,
蒂亞戈

0

您需要將數據包裝到另一個具有DataTemplate複選框可綁定屬性的類中。

例如:

<ItemsControl ItemsSource="{Binding YourList}"> 
    <ItemsControl.ItemTemplate> 
    <DataTemplate> 
     <CheckBox Content="{Binding TextValue}" 
       IsChecked="{Binding IsChecked}" /> 
    </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

在IEnumerable的視圖模型爲每個項目可能看起來像:

class Checkable : ViewModelBase { 

    private bool _isChecked; 
    private string _textValue; 

    public bool IsChecked { 
     get { 
     return _isChecked; 
     } 
     set { 
     _isChecked = value; 
     OnPropertyChanged("IsChecked"); 
     } 
    } 

    public string TextValue { 
     get { 
     return _textValue; 
     } 
     set { 
     _textValue = value; 
     } 
    } 
    } 

視圖模型爲您的用戶控件將有一個IEnumerable,如:

public List<Checkable> YourList; 

無論您使用ListBox還是ItemsControl,都是您使用哪種類型的功能e尋找(我認爲ItemsControl是你在這裏尋找的東西)。

相關問題