为什么Combobox.FindName()方法总是返回null? [英] Why does the Combobox.FindName() method always return null?

查看:338
本文介绍了为什么Combobox.FindName()方法总是返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在List对象中定义了Combobox的ItemSource。我想通过使用FindName()方法到达ComboBoxItem,但它总是返回null。我已经尝试ApplyTemplate()在开始,我也试图到达使用Combobox.Template项目。这里是我的代码。有什么建议么?

 列表< string& subjectsList = e.Result; 
cbCategory.ItemsSource = subjectsList;
cbCategory.SelectedItem = cbCategory.FindName(DefaultChatSubject);

顺便说一下,我对ItemSource中的Items没有任何问题。

解决方案

FrameworkTemplate.FindName 方法 所提供的标识符名称。从MSDN上的链接页面:


如果元素具有子元素,则所有这些子元素都将被递归搜索所请求的命名元素。 / p>

FindName在当前元素的namescope中运行。有关详细信息,请参见 WPF XAML命名目录


为了成功使用 FindName 方法,您正在寻找的子元素必须设置其 Name 属性。由于数据绑定的项集合不太可能具有 ComboBoxItem.Name 属性集,因此也不太可能为您工作。



设置所选项的更好方法是这样:

  cbCategory.SelectedItem = subjectList.First(i => i.Property ==DefaultChatSubject); 

或者如果你的集合项只是 string s,像这样:

  cbCategory.SelectedItem =DefaultChatSubject 


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.

解决方案

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

这篇关于为什么Combobox.FindName()方法总是返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆