将字符串传递给另一个 class

Passing string to another class

在 MyViewModel 中,我有一个字符串 属性 (SearchBox) 绑定到我视图中的文本框。当我单击搜索按钮时,命令发送到我的数据层 class 以从 dB 获取搜索结果(图像)。

我的问题是如何从搜索框传递字符串以及在数据层中使用的方法class。

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 中 class 我需要在查询中使用 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 中搜索数据库Class?

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

public ObservableCollection<Image> FindVisualReferences(string search)

现在,调用此方法时只需传入 SearchBox 字符串即可,如下所示:

FindVisualReferences = dbFunctions.FindVisualReferences(SearchBox);

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

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

现在,@Floris 提出了使用 参数 而不是字符串连接的一个很好的观点,我建议查看 this,因为它已经得到解答。