WPF简单查询
Model层
public class Dish
{
public string Name { get; set; }
public string Category { get; set; }
public string Comment { get; set; }
public double Score { get; set; }
}
Service层
public interface IDishService
{
List<Dish> SelectDishByName(string Name);
}
public class DishService : IDishService
{
SqlConnection conn = new SqlConnection(@"Data Source=.;Initial Catalog=CrazyElephant;User ID=sa;Password=123456");
public List<Dish> SelectDishByName(string Name)
{
conn.Open();
string sql = "select * from Dish where Name = @Name";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Name",Name);
List<Dish> list = new List<Dish>();
if (!string.IsNullOrEmpty(Name))
{
using (SqlDataReader item = cmd.ExecuteReader())
{
while (item.Read())
{
Dish entity = new Dish();
entity.Name = item["Name"].ToString();
entity.Comment = item["Comment"].ToString();
entity.Category = item["Category"].ToString();
entity.Score = double.Parse(item["Score"].ToString());
list.Add(entity);
}
}
}
return list;
}
}
ViewModel层
// 继承prism.DryIoc中的BindableBase
public class MainWindowViewModel : BindableBase
{
public MainWindowViewModel()
{
this.SelectDishByName();
// 重载
this.SelectDishByNameCommand = new DelegateCommand(new Action(this.SelectDishByName));
}
public string TextName { get; set; }
public DelegateCommand SelectDishByNameCommand { get; set; }
private List<Dish> dishMenu;
public List<Dish> DishMenu
{
get { return dishMenu; }
set { dishMenu = value; RaisePropertyChanged(); }
}
private void SelectDishByName()
{
DishService ds = new DishService();
var dishes = ds.SelectDishByName(this.TextName);
// 实例化
this.DishMenu = new List<Dish>();
// 遍历数组
foreach (var dish in dishes)
{
this.DishMenu.Add(dish);
}
}
}
VIew层
<StackPanel>
<TextBox x:Name="Names" Height="30" Width="80" Margin="5" Text="{Binding TextName}"/>
<Button Height="30" Width="100" Command="{Binding SelectDishByNameCommand}"/>
<DataGrid AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False"
GridLinesVisibility="None" Margin="0,4" FontSize="16" ItemsSource="{Binding DishMenu}">
<DataGrid.Columns>
<DataGridTextColumn Header="菜品" Binding="{Binding Name}" Width="120"/>
<DataGridTextColumn Header="种类" Binding="{Binding Category}" Width="120"/>
<DataGridTextColumn Header="点评" Binding="{Binding Comment}" Width="120"/>
<DataGridTextColumn Header="推荐分数" Binding="{Binding Score}" Width="120"/>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
最后:MainWindow
this.DataContext = new MainWindowViewModel();