我使用一個隱藏的文本框,在用戶輸入時短暫出現,並在幾秒鐘後重置並清除,以便在定時器到期後不嘗試匹配其內容。該人將輸入列表框,並且由於在SearchText
上的綁定,其事件將填充文本框。當SearchText
被填充時,它觸發MyFilteredItems()
在該文本和列表框之間執行匹配。然後,如果用戶按Enter,則選擇將進入另一個TextBox(未在XAML中列出,但在代碼中註釋時提供),並從lstPickList
中清除。 TextBox然後被清除並且定時器重置。
XAML:
<TextBox Name="txtPicker" IsReadOnly="True" Foreground="LightGreen" FontFamily="Consolas" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}"></TextBox>
<ListBox Name="lstPickList" Grid.Row="1" ItemsSource="{Binding MyFilteredItems}" KeyUp="lstPickList_KeyUp"></ListBox>
然後這是相關的代碼隱藏:
public partial class MainWindow : Window, INotifyPropertyChanged
{
private Timer t = new Timer();
public System.Windows.Threading.DispatcherTimer tCleanup =
new System.Windows.Threading.DispatcherTimer();
private string _searchText;
public string SearchText
{
get { return _searchText; }
set
{
_searchText = value;
OnPropertyChanged("SearchText");
OnPropertyChanged("MyFilteredItems");
}
}
public List<string> MyItems { get; set; }
public IEnumerable<string> MyFilteredItems
{
get
{
if (SearchText == null) return MyItems;
return MyItems.Where(x => x.ToUpper().StartsWith(SearchText.ToUpper()));
}
}
public MainWindow()
{
InitializeComponent();
MyItems = new List<string>() { "ABC", "DEF", "GHI" };
this.DataContext = this;
t.Interval = 1000;
t.Elapsed += new ElapsedEventHandler(timerCounter);
tCleanup.Interval = new TimeSpan(0,0,1);
tCleanup.Tick += new EventHandler(cleanupCounter_Tick);
txtPicker.Visibility = Visibility.Collapsed;
tCleanup.Start();
}
private static int counter = 0;
protected void timerCounter(object sender, ElaspedEventArgs e)
{
counter++;
}
protected void cleanupCounter_Tick(object sender, EventArgs e)
{
if (counter > 2 && txtPicker.Visibility == Visibility.Visible)
txtPicker.Visibility = Visibility.Collapsed;
}
private void lstPickList_KeyUp(object sender, KeyEventArgs e)
{
ListBox lst = (ListBox)sender;
string strg = Convert.ToString(e.Key.ToString().Replace("D",""));
if (counter < 2)
{
txtPicker.Visibility = Visibility.Visible;
t.Start();
if (strg == "Return")
{
txtPicker.Text += "{Enter}";
SearchText += "{Enter}";
}
else
{
txtPicker.Text += strg;
SearchText += strg;
}
}
else
{
SearchText = strg;
txtPicker.Text = strg;
t.Stop();
counter = 0;
t.Start();
}
if (strg == "Return")
{
// This next line would be if you had a "selected items" ListBox to store the item
// lstSelectedList.Items.Add(lstPickList.SelectedItem);
lstPickList.Items.Remove(lstPickList.SelectedItem);
t.Stop();
txtPicker.Visibility = Visibility.Collapsed;
counter = 0;
txtPicker.Text = String.Empty;
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string name)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
這正是我一直在尋找。謝謝。 – Nate 2010-11-17 23:43:27