gpt4 book ai didi

c# - 如何过滤 AutoCompleteBox 中第一个匹配项的项目列表?

转载 作者:太空宇宙 更新时间:2023-11-03 13:31:21 25 4
gpt4 key购买 nike

我的目标是允许用户点击 Tab 键和自动完成框以立即选择下拉列表中的第一项。问题是我似乎无法弄清楚如何访问第一个过滤项目。有什么想法吗?

起初我以为属性 IsTextCompletionEnabled = true 可以解决我的问题。但是,如果我使用 FilterMode = Contains,文本完成功能将无济于事,因为什么都没有完成。

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>

最佳答案

您只需将谓词传递给 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));
}
}

这样,所选项目将是第一个匹配谓词的项目,或者在这种情况下,项目名称或艺术家包含文本框中当前值的第一个。

关于c# - 如何过滤 AutoCompleteBox 中第一个匹配项的项目列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20425635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com