Why does the Combobox.FindName() method always ret

2019-09-06 07:08发布

问题:

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.

回答1:

The FrameworkTemplate.FindName Method Finds an element that has the provided identifier name. 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 WPF XAML Namescopes.

In order to use the FindName method successfully, the child element that you are looking for must 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 strings, like this:

cbCategory.SelectedItem = "DefaultChatSubject";


回答2:

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";