Why does the Combobox.FindName() method always return null?

纵然是瞬间 提交于 2019-12-25 02:39:10

问题


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


来源:https://stackoverflow.com/questions/21476979/why-does-the-combobox-findname-method-always-return-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!