【问题标题】:Passing string to another class将字符串传递给另一个类
【发布时间】: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


【解决方案1】:

首先,改变你的方法来接受一个字符串参数:

public ObservableCollection<Image> FindVisualReferences(string search)

现在,您可以在调用此方法时简单地传入SearchBox 字符串,如下所示:

FindVisualReferences = dbFunctions.FindVisualReferences(SearchBox);

然后您可以重写查询以引用参数,如下所示:

string Query = "Select* from images where title = '" + search.ToUpper() + "'";

现在,@Floris 提出了使用 parameters 而不是字符串连接的好方法,我建议您查看this,因为它已经得到了回答。

【讨论】:

    猜你喜欢
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 2018-12-13
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    相关资源
    最近更新 更多