
Question:
I have defined Combobox's ItemSource in List object. I want to reach the ComboBoxItem by using FindName() method but it always returns null. I have tried ApplyTemplate() at the beginning and I also have tried to reach the Item using Combobox.Template. Here is my code. Any suggestions?
List<string> subjectsList = e.Result;
cbCategory.ItemsSource = subjectsList;
cbCategory.SelectedItem = cbCategory.FindName("DefaultChatSubject");
By the way, I do not have any problem about the Items in ItemSource.
Answer1:The <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworktemplate.findname%28v=vs.110%29.aspx" rel="nofollow">FrameworkTemplate.FindName
Method</a> <em>Finds an element that has the provided identifier name</em>. From the linked page on MSDN:
If the element has child elements, these child elements are all searched recursively for the requested named element.
FindName operates within the current element's namescope. For details, see <a href="http://msdn.microsoft.com/en-us/library/ms746659.aspx" rel="nofollow">WPF XAML Namescopes</a>.
</blockquote>In order to use the FindName
method successfully, the child element that you are looking for <em>must</em> have their Name
property set. As it is somewhat unlikely that a data bound collection of items will have the ComboBoxItem.Name
property set, it is also unlikely that this will work for you.
A better way to set the selected item is like this:
cbCategory.SelectedItem = subjectsList.First(i => i.Property == "DefaultChatSubject");
Or if your collection items are just string
s, like this:
cbCategory.SelectedItem = "DefaultChatSubject";
Answer2:FindName
is meant to find a named child element of a FrameworkElement. It does not find an item string in the Items collection of an ItemsControl (like your ComboBox).
You could simply call this instead:
cbCategory.SelectedItem = "DefaultChatSubject";