WpfMdict / csharp /mdict /Views /SearchView.xaml.cs
fasdfsa's picture
改用 chrome 显示查询结果
6667126
using System.Linq;
using System.Windows.Controls;
using System.Windows.Input;
using mdict.Services;
using Mdx.Storage;
using CefSharp;
namespace mdict.Views
{
public class SearchResult
{
public string Key => KeyIndex.Key;
public string DisplayText => $"{Key} - {Dictionary.Name}";
public KeyIndex KeyIndex { get; set; }
public DictionaryItem Dictionary { get; set; }
}
public partial class SearchView : UserControl
{
public SearchView()
{
InitializeComponent();
}
private void SearchInput_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
var query = SearchInput.Text.Trim();
if (string.IsNullOrWhiteSpace(query)) return;
var results = LibraryManager.Instance.Search(query);
var viewResults = results.Select(r => new SearchResult
{
Dictionary = r.Dictionary,
KeyIndex = r.Index
}).ToList();
ResultList.ItemsSource = viewResults;
if (viewResults.Any())
{
ResultList.SelectedIndex = 0;
}
}
}
private void ResultList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ResultList.SelectedItem is SearchResult item)
{
PlaceholderText.Visibility = System.Windows.Visibility.Collapsed;
ContentBrowser.Visibility = System.Windows.Visibility.Visible;
try
{
string content = item.Dictionary.Reader.GetHtml(item.KeyIndex);
// Use LoadHtml from CefSharp
// Providing a dummy URL is often helpful for resolving relative links or just identifying the source
ContentBrowser.LoadHtml(content, "http://mdict/" + item.Key);
}
catch (System.Exception ex)
{
ContentBrowser.LoadHtml($"<h1>Error</h1><p>{ex.Message}</p>", "http://error/");
}
}
}
}
}