我有一個文本框將保留最後輸入的10個條目,類似於Internet Explorer中的搜索框。用戶可以點擊下拉菜單查看最後10個條目。下拉菜單是一個組合框。我創建了一個綁定到組合框的字符串的Observable集合Itemssource.Below是代碼。存儲組合框的文本條目
的XAML
<Grid x:Name="TextBox_grid" Margin="0,0,40,0" Width="360" Height="23">
<ComboBox Name="cb" Margin="0,0,-29,0" Style="{DynamicResource Onyx_Combo}" ItemsSource="{Binding TextEntries, ElementName=TheMainWindow, Mode=OneWay}" IsEditable="False" Visibility="Visible" />
<Rectangle Fill="#FF131210" Stroke="Black" RadiusX="2" RadiusY="2"/>
<TextBox Name=UniversalTextBox Margin="0" Background="{x:Null}" BorderBrush="{x:Null}" FontSize="16" Foreground="#FFA0A0A0" TextWrapping="Wrap" PreviewKeyDown="TextBox_PreviewKeyDown"/>
</Grid>
代碼
public partial class Window1 : Window
{
private ObservableCollection<string> m_TextEntries = new ObservableCollection<string>();
public Window1()
{
InitializeComponent();
}
public ObservableCollection<string> TextEntries
{
get { return m_TextEntries; }
}
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox == null)
return;
if (e.Key == Key.Enter)
{
PopulateHistoryList(textBox.Text);
e.Handled = true;
}
if (e.Key == Key.Escape)
{
e.Handled = true;
}
}
private void PopulateHistoryList(string text)
{
m_TextEntries.Add(text);
}
private event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
上面的代碼將填充TextEntries集合時,按鍵上的文本框中輸入。我需要兩件東西
- 如何設置組合框的選定項目,以及如何將其綁定到我的文本框。
- 組合框(dropmenu)應該只顯示下拉菜單中的最後10個條目。
由於提前,