我的目标是允许用户点击Tab键和自动填充框,立即选择下拉列表中的第一个项目。问题是我似乎无法弄清楚如何访问第一个过滤的项目。有什么想法吗?
起初我认为属性IsTextCompletionEnabled = true会解决我的问题。但是,如果我使用FilterMode = Contains,则textcompletion功能无效,因为没有任何内容完成。
ItemsSource实际上并没有改变。我需要到达筛选列表中的第一项而不是itemssource。有办法吗?
这是我的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Recording> MyMusic = new List<Recording>();
MyMusic.Add(new Recording("Chris Sells", "Chris Sells Live", new DateTime(2008, 3, 5)));
MyMusic.Add(new Recording("Chris Sells", "CSells Tells", new DateTime(2004, 4, 6)));
MyMusic.Add(new Recording("Luka Abrus", "The Road to Redmond", new DateTime(2007, 8, 3)));
MyMusic.Add(new Recording("Luka Abrus", "CLuka", new DateTime(2005, 12, 8)));
MyMusic.Add(new Recording("Luka Abrus", "CLove and Luka", new DateTime(2005, 12, 8)));
MyMusic.Add(new Recording("Jim Hance", "The Best of Jim Hance", new DateTime(2007, 2, 6)));
Records.ItemsSource = MyMusic;
}
private void Records_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
Records.SelectedItem = ((IEnumerable<object>)Records.ItemsSource).First();
}
}
public class Recording
{
public Recording() { }
public Recording(string artistName, string cdName, DateTime release)
{
Artist = artistName;
Name = cdName;
ReleaseDate = release;
}
public string Artist { get; set; }
public string Name { get; set; }
public DateTime ReleaseDate { get; set; }
}
这是xaml:
<Controls:AutoCompleteBox x:Name="Records" HorizontalAlignment="Left" Margin="164,142,0,0" VerticalAlignment="Top" Width="182"
ValueMemberPath="Name" KeyDown="Records_KeyDown"
FilterMode="Contains"
IsTextCompletionEnabled="True">
<Controls:AutoCompleteBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</Controls:AutoCompleteBox.ItemTemplate>
</Controls:AutoCompleteBox>
答案 0 :(得分:2)
您只需将谓词传递给First
方法,
private void Records_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
Records.SelectedItem =
Records.ItemsSource
.First(item =>
item.Name.Contains(textBoxValue) ||
item.Artist.Contains(textBoxValue));
}
}
这样,所选项目将是第一个与谓词匹配的项目,或者在这种情况下,第一个项目名称或艺术家包含文本框中当前值的项目。
答案 1 :(得分:-1)
Records.SelectedItem = Records.Items [0]; ?