我是异步方法的新手,正在努力解决这样一个问题(我为我的问题做了一个简单的例子):
假设我有一个ComboBox,其中的Item与一个***BindableCollection NameList***绑定,其中的Item是一些名称。
<ComboBox
x:Name="SubbranchComboBox"
Margin="20 0 0 0"
Width="100"
Height="20"
IsEnabled="True"
IsEditable="True"
IsTextSearchEnabled="False"
InputScope="Xml"
ItemsSource="{Binding NameList}" KeyUp="ComboBox_KeyUp">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
ComboBox_KeyUp如下所示:
private void ComboBox_KeyUp(object sender, KeyEventArgs e)
{
var combobox = (ComboBox)sender;
var ctb = combobox.Template.FindName("PART_EditableTextBox", combobox) as TextBox;
if (ctb == null) return;
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift) || Keyboard.Modifiers.HasFlag(ModifierKeys.Control) || Keyboard.Modifiers.HasFlag(ModifierKeys.Alt))
return;
var caretPos = ctb.CaretIndex;
var searchedText = combobox.Text.ToLower();
combobox.SelectedIndex = -1;
combobox.IsDropDownOpen = true;
CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(combobox.Items);
itemsViewOriginal.Filter = ((o) =>
{
if (String.IsNullOrEmpty(searchedText))
{
return true;
}
else
{
if (((string)o).ToLower().Contains(searchedText.ToLower()))
{
return true;
}
else
{
return false;
}
}
});
itemsViewOriginal.Refresh();
ctb.CaretIndex = caretPos;
}
并在组合框中充当键入短语的搜索函数。问题是,我希望过滤是异步完成的,但每当我尝试这样做时,我都会得到一个错误:调用线程无法访问此对象,因为另一个线程拥有它
请给予我一些建议,它应该如何做.所有的示例代码:
public partial class MainWindow : Window
{
public BindableCollection<String> NameList { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
NameList = new BindableCollection<String>
{
"Tony",
"Jerry",
"George",
"Harry",
"Snape",
"Sirius",
"Dan",
"Michael",
"Mike",
"Sebastian",
"Simon",
"Johny"
};
}
private void ComboBox_KeyUp(object sender, KeyEventArgs e)
{
var combobox = (ComboBox)sender;
var ctb = combobox.Template.FindName("PART_EditableTextBox", combobox) as TextBox;
if (ctb == null) return;
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift) || Keyboard.Modifiers.HasFlag(ModifierKeys.Control) || Keyboard.Modifiers.HasFlag(ModifierKeys.Alt))
return;
var caretPos = ctb.CaretIndex;
var searchedText = combobox.Text.ToLower();
combobox.SelectedIndex = -1;
combobox.IsDropDownOpen = true;
CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(combobox.Items);
itemsViewOriginal.Filter = ((o) =>
{
if (String.IsNullOrEmpty(searchedText))
{
return true;
}
else
{
if (((string)o).ToLower().Contains(searchedText.ToLower()))
{
return true;
}
else
{
return false;
}
}
});
itemsViewOriginal.Refresh();
ctb.CaretIndex = caretPos;
}
}
1条答案
按热度按时间5vf7fwbs1#
问题是,我希望过滤是异步完成的,但是每当我尝试这样做时,我都会得到一个错误:调用线程无法访问此对象,因为其他线程拥有它
如果要从后台线程更新UI,则应在应用程序的调度程序中运行代码