我目前正在制作一个简单的工具,允许您一次进行不同类型的搜索。到目前为止,我已经通过实现一个 Site 类、创建一个我想要搜索的站点列表、然后打开一个带有 Browser 元素的新窗口以及每个活动站点所需的搜索 URL 来完成此操作。
还有一种方法可以创建一个新站点并将其添加到列表中。
网站.cs
public class Site
{
public int type { get; set; }
public string URL { get; set; }
public string extras { get; set; }
public string name { get; set; }
public bool IsChecked { get; set; }
public Uri GetMySearch(string query)
{
switch (type)
{
case 0: //Simple Search
return new Uri(URL + query);
case 1: //API call
return new Uri(URL + query + extras);
default: return null;
}
}
}
Mainwindow.Cs 的某些部分
private void Window_Loaded(object sender, RoutedEventArgs e) //initialization
{
Site Google = new Site();
Google.URL = "https://google.com/search?q=";
Google.type = 0;
Google.name = "google";
Site Wolfram = new Site();
Wolfram.URL = "https://api.wolframalpha.com/v1/simple?i=";
Wolfram.type = 1;
Wolfram.extras = "&appid=2GA4A5-YL7HY9KR42";
Wolfram.name = "Wolfram";
Site Wikipedia = new Site();
Wikipedia.URL = "https://google.com/search?q=site:wikipedia.org";
Wikipedia.type = 0;
Wikipedia.name = "Wikipedia";
sites.Add(Google);
sites.Add(Wolfram);
sites.Add(Wikipedia);
SitesDisplay.ItemsSource = sites;
}
private void AddNewSiteButton(object sender, RoutedEventArgs e)
{
SiteEntryWindow siteEntryWindow = new SiteEntryWindow("Enter the display name of your site \nOr leave blank to default to URL");
if (siteEntryWindow.ShowDialog() == true)
{
if (siteEntryWindow.url.Length > 3)
AddASite(siteEntryWindow.url, siteEntryWindow.MyName);
else MessageBox.Show("Please enter a valid url!", "Oops!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
public void AddASite(string url, string name = "")
{
Site mySite = new Site();
if (name.Length > 0)
mySite.name = name;
else mySite.name = url;
mySite.URL = "https://google.com/search?q=site:" + url;
mySite.type = 0;
sites.Add(mySite);
SitesDisplay.ItemsSource = null;
SitesDisplay.ItemsSource = sites;
}
本质上,我试图弄清楚如何将站点的用户列表保存到 txt 文件(或在这种情况下更适用的文件),然后在应用程序打开时加载它。我尝试使用 StreamWriter 和 WriteAllLines,但由于它是网站列表,他们不知道该怎么做。
我可能会使用大量 if else 将每个单独的类属性处理为字符串,然后将其写入 txt 文件,但每当我想加载时我都必须解析它,我无法想象这会很容易。
这个人似乎遇到了类似的问题,但我不确定 XML 文件是否是最好的解决方案,而且XmlSerializer似乎超出了我的范围。有没有更简单/更好的方法来做到这一点?
如果这是一个愚蠢的问题或有一个简单的解决方案,我对 C# 和 WPF 仍然有些陌生,很抱歉。