【发布时间】:2015-07-08 05:33:38
【问题描述】:
在 MyViewModel 中,我有一个字符串属性 (SearchBox),它绑定到我的视图中的文本框。当我单击搜索按钮时,A 命令会发送到我的数据层类以从 dB 中获取搜索结果(图像)。
我的问题是如何从 searchBox 传递字符串以及在数据层类中使用的方法。
public class MyViewModel : NotifyUIBase
{
private string _searchBox;
public string SearchBox // the Name property
{
get { return this._searchBox; }
set { this._searchBox = value; RaisePropertyChanged(); }
}
public MyViewModel()
{
FindImageCommand = new RelayCommand(FindImage);
}
public RelayCommand FindImageCommand { get; private set; }
private void FindImage()
{
var dbFunctions = new DatabaseFunctions();
FindVisualReferences = dbFunctions.FindVisualReferences();
}
}
在 DataLayer 类中,我需要使用查询中 SearchBox 中的字符串来搜索 dB。
public class DataLayer
{
public ObservableCollection<Image> FindVisualReferences()
{
var FindVisualReferences = new ObservableCollection<Image>();
String dbConnectionString = @"Data Source =mydB.sqlite";
SQLiteConnection cnn = new SQLiteConnection(dbConnectionString);
cnn.Open();
====> string Query = "Select* from images where title = '" + SearchBox.ToUpper() + "'";
SQLiteDataAdapter sda = new SQLiteDataAdapter(Query, cnn);
DataTable dt = new DataTable();
sda.Fill(dt);
// rest of dB method
}
}
如何从 MyViewModel 中的 SearchBox 中获取字符串到查询中以在 DataLayer 类中搜索数据库?
【问题讨论】:
-
请说明您尝试了什么,做了什么,以及它与您想要的有何不同。一定要包括a good, minimal, complete code example 来说明所有这些。特别是,请清楚地解释为什么您不能只将值传递给
FindVisualReferences()方法,就像人们通常在他们希望调用某个方法以访问它需要的某些特定值时所做的那样。 -
正如@PeterDuniho 所说,只需传递 dbFunctions.FindVisualReferences(SearchBox)。也不要像这样连接一个 sql 查询,它会为 sql 注入打开它。使用参数!使用 SQLiteCommand,并添加参数。
标签: c# wpf sqlite mvvm binding