Combobox Datatemplate in Code-Behind
-
My datatemplate for combobox is as below: <DataTemplate x:Key="Template_ComboBoxItem"> <CheckBox Name="CbName" > <TextBlock Name="tbName" Margin="5,0,5,0" Text="{Binding Name}"/> </CheckBox> </DataTemplate> I want to get the checkBox status(checked or not) from ComboBoxItem for ex: 1 item.. cbi = this.cmbArea.ItemContainerGenerator.ContainerFromItem(entity) as System.Windows.Controls.ComboBoxItem; ContentPresenter contentPresenter = this.FindVisualChild<ContentPresenter>(cbi); contentPresenter.ApplyTemplate(); DataTemplate cellTemplate = this.cmbArea.ItemTemplate; DependencyObject child = VisualTreeHelper.GetChild(contentPresenter, 0); cbName = cellTemplate.FindName("CbName", (FrameworkElement)child) as System.Windows.Controls.CheckBox; The last line throws exception: This operation is valid only on elements that have this template applied. Any mistake???
-
My datatemplate for combobox is as below: <DataTemplate x:Key="Template_ComboBoxItem"> <CheckBox Name="CbName" > <TextBlock Name="tbName" Margin="5,0,5,0" Text="{Binding Name}"/> </CheckBox> </DataTemplate> I want to get the checkBox status(checked or not) from ComboBoxItem for ex: 1 item.. cbi = this.cmbArea.ItemContainerGenerator.ContainerFromItem(entity) as System.Windows.Controls.ComboBoxItem; ContentPresenter contentPresenter = this.FindVisualChild<ContentPresenter>(cbi); contentPresenter.ApplyTemplate(); DataTemplate cellTemplate = this.cmbArea.ItemTemplate; DependencyObject child = VisualTreeHelper.GetChild(contentPresenter, 0); cbName = cellTemplate.FindName("CbName", (FrameworkElement)child) as System.Windows.Controls.CheckBox; The last line throws exception: This operation is valid only on elements that have this template applied. Any mistake???
First, where is the above code running? Which event handler? Second, why not just loop through the Items collection in the ComboBox and check each CheckBox? Then you won't need all that code. Get Mole or Snoop and have a look at your application's Visual Tree so that you can understand what your looping through. It is very easy once you understand this.
Cheers, Karl
» CodeProject 2008 MVP » Microsoft MVP - Client App Dev My Blog | Mole's Home Page | MVP ProfileJust a grain of sand on the worlds beaches.