2012-03-12 55 views
2

我的代碼如下。訪問WPF列表框內的複選框

<ListBox x:Name="lstBoxMarket" BorderThickness="0" Height="Auto" HorizontalAlignment="Center" Width="200" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"> 
    <ListBox.ItemTemplate> 
     <HierarchicalDataTemplate> 
      <CheckBox IsChecked="{Binding Checked}" CommandParameter="{Binding MarketId}" Tag="{Binding MarketId}" Content="{Binding Market}" Foreground="#FF3D66BE" Name="chkMarket"/> 
     </HierarchicalDataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

我想訪問保存按鈕單擊列表中選中和取消選中的複選框。我無法直接訪問chkMarket。誰能幫忙?

+2

您在代碼中擁有'{Binding Checked}'語句,這意味着您將其綁定到視圖模型並將其列表存儲在某處。什麼是lstBoxMarket的DataContext? – vorrtex 2012-03-12 06:34:47

回答

1

由於它是2路綁定我可以訪問從列表框的項目源複選框中選擇的值。 DataTable lstBoxMarketItemSourceDT =((DataView)lstBoxMarket.ItemsSource).ToTable();

檢索到的數據表中的「已檢查」列給出了已更新的複選框值。

1

從您的代碼開始,我嘗試過類似的東西

    // find all T in the VisualTree 
       public static IEnumerable<T> FindVisualChildren<T>(DependencyObject parent) 
     where T : DependencyObject 
    { 
     List<T> foundChilds = new List<T>(); 

     int childrenCount = VisualTreeHelper.GetChildrenCount(parent); 
     for (int i = 0; i < childrenCount; i++) 
     { 
      var child = VisualTreeHelper.GetChild(parent, i); 

      T childType = child as T; 
      if (childType == null) 
      { 
       foreach(var other in FindVisualChildren<T>(child)) 
        yield return other; 
      } 
      else 
      { 
       yield return (T)child; 
      } 
     } 
    } 

然後在你的主窗口

private void button1_Click(object sender, RoutedEventArgs e) 
    { 
          // find all checkboxes in my window 
     IEnumerable<CheckBox> myBoxes = FindVisualChildren<CheckBox>(this); 

     int numChecked = 0; 
     foreach(CheckBox cb in myBoxes) 
     { 
      if(cb.Name != "chkMarket") 
       continue; 


      if (cb.IsChecked == true) 
       numChecked++; 

     } 

     MessageBox.Show("Checked items = " + numChecked); 


    } 

我的視圖模型的代碼是

public class ViewModel 
{ 
    public ViewModel() 
    { 
     _persons = new ObservableCollection<Person>(); 
     _persons.Add(new Person() { Name = "Paul", Checked = false }); 
     _persons.Add(new Person() { Name = "Brian", Checked = true }); 
    } 

    private ObservableCollection<Person> _persons; 

    public ObservableCollection<Person> Persons 
    { 
     get { return _persons; } 
    } 
} 

public class Person 
{ 
    public String Name { get; set; } 
    public Boolean Checked { get; set; } 
} 

你應該能夠看到消息「選中的項目= 1」。 希望這可以幫助

+0

每當你使用'VisualTreeHelper'的機會是,你正在做*錯* *。在這種情況下,可以通過綁定對象輕鬆訪問所需的值,WPF中很少需要對控件的直接訪問。 – 2012-03-14 14:30:17