我有这段代码:
if (((Classes.ProductGroup)o).ToString().Contains(comboBox.Text))
return true;
else
return false;
现在我不想指定部件Classes.ProductGroup
。我想让它具有普遍性。
如何使用Classes.ProductGroup
对象替换部件Type
?
Type type = typeof(Classes.ProductGroup);
类似的东西:
if (((type)o).ToString().Contains(comboBox.Text))
这可能吗?
以下是完整的方法代码:
private void FilterPGsinComboBox(object obj)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(new FilterPGsinComboBoxDelegate(this.FilterPGsinComboBox),obj);
return;
}
Type type = ((Dictionary<ComboBox, Type>)obj).First().Value;
ComboBox comboBox = ((Dictionary<ComboBox, Type>)obj).First().Key;
comboBox.IsDropDownOpen = true;
CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(comboBox.ItemsSource);
itemsViewOriginal.Filter = ((o) =>
{
if (String.IsNullOrEmpty(comboBox.Text))
return true;
else
{
if (((Classes.ProductGroup)o).ToString().Contains(comboBox.Text))
return true;
else
return false;
}
});
itemsViewOriginal.Refresh();
}
答案 0 :(得分:1)
您可以使用泛型并构建类似
的方法<style>
如果要使此方法不区分大小写,请将逻辑更改为
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script>
function onlyAlphabet(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
var keychar = String.fromCharCode(key);
var keycheck = /[a-zA-z\s]/;
if (!(key == 8 || key == 27 || key == 46 || key == 9 || key == 39 || key == 94)) // backspace delete escape arrows
{
if (!keycheck.test(keychar)) {
theEvent.returnValue = false;//for IE
if (theEvent.preventDefault)
theEvent.preventDefault();//Firefox
}
}
else if(key==94)
theEvent.preventDefault();
}
</script>
</head>
<body>
<input id="Text1" type="text" onkeypress="return onlyAlphabet(event)"/>
</body>
</html>
答案 1 :(得分:1)
string ToString()
方法在基础Object
类中定义。铸造成混凝土类型是多余的。
string filter = comboBox.Text;
itemsViewOriginal.Filter = o => String.IsNullOrEmpty(filter) ||
o != null && o.ToString().Contains(filter);