2016-03-10 52 views
0
<TreeView x:Name="foldersItem"> 
     <TreeView.Resources> 
      <Style TargetType="{x:Type TreeViewItem}"> 
       <Setter Property="HeaderTemplate"> 
        <Setter.Value> 
         <DataTemplate> 
          <StackPanel Orientation="Horizontal"> 
           <CheckBox Name="cbItem"></CheckBox> 
           <TextBlock Text="{Binding}" Margin="5,0" /> 
          </StackPanel> 
         </DataTemplate> 
        </Setter.Value> 
       </Setter> 
      </Style> 
     </TreeView.Resources> 
    </TreeView> 

基本上我在上面的代碼中有一個TreeView,並且每個TreeViewItem都有一個複選框和一個文本塊。我如何訪問,檢查或取消選中每個TreeViewItem的複選框? 我猜我需要某種綁定,但我無法將自己的想法包裝在什麼或如何。 最終結果應該有一個Windows窗體類型的TreeView,其複選框分別設置爲true或false。如何訪問wpf中的目標類型的DataTemplate項目

如果我對這一切都有錯,請告訴我。如果您需要更多信息,我很樂意提供。

回答

1

您可以通過ItemsControl的典型數據綁定模式來設置或獲取CheckBox的值。以下是最低限度的例子。背後

代碼:

using System.Collections.ObjectModel; 
using System.ComponentModel; 
using System.Windows; 

namespace WpfApplication1 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     public ObservableCollection<ItemViewModel> Items { get; } = 
      new ObservableCollection<ItemViewModel> 
      { 
       new ItemViewModel { Name = "Item1", IsChecked = null }, 
       new ItemViewModel { Name = "Item2", IsChecked = true }, 
       new ItemViewModel { Name = "Item3", IsChecked = false } 
      }; 
    } 

    public class ItemViewModel : INotifyPropertyChanged 
    { 
     public string Name { get; set; } 

     private bool? _isChecked; 
     public bool? IsChecked 
     { 
      get { return _isChecked; } 
      set 
      { 
       _isChecked = value; 
       OnPropertyChanged(nameof(IsChecked)); 
      } 
     } 

     public event PropertyChangedEventHandler PropertyChanged; 
     private void OnPropertyChanged(string propertyName) => 
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

的XAML:

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     x:Name="WindowRoot" 
     Title="MainWindow" Height="300" Width="400"> 
    <Grid> 
     <TreeView ItemsSource="{Binding ElementName=WindowRoot, Path=Items}"> 
      <TreeView.ItemTemplate> 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal"> 
         <CheckBox IsChecked="{Binding IsChecked}"/> 
         <TextBlock Text="{Binding Name}"/> 
        </StackPanel> 
       </DataTemplate> 
      </TreeView.ItemTemplate> 
     </TreeView> 
    </Grid> 
</Window> 

訪問ItemViewModel的IsChecked屬性來設置或獲取複選框的值。

+0

我想我可以用這個工作,並讓它做我需要的:) 謝謝! –

相關問題