在WPF的MVVM设计中有仅有一个控件ComboBox,其IsEditable属性设置为true,该控件绑定后台ViewModel中的数据类型是public ObservableCollection<string> Source,Source的来源是sqlite数据库中的MSJ.db数据库的表Source的数据,该表只有一列数据,列名为Source,表里有两行数据分别为“上级配发”和“本级自购”,要求实现第一点:ComboBoxItem选择发生改变时,弹窗提示用户选择前后的数据;第二点:ComboBox的输入框在接受自定义输入后,判断用户输入不属于ComboBoxItem后,自动将其加入ComboBoxItem中,同时更新后台sqlite数据库的MSJ.db数据库的表Source的数据。请给出实现上述功能的完整实例代码
时间: 2024-02-12 17:02:36 浏览: 20
以下是实现上述功能的完整实例代码:
XAML代码:
```xml
<Window x:Class="ComboBoxDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ComboBox Demo" Height="150" Width="300">
<Grid>
<ComboBox x:Name="comboBox" Margin="10" IsEditable="True"
ItemsSource="{Binding Source}" SelectedItem="{Binding SelectedItem}"
Text="{Binding Text}">
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<EventSetter Event="Selected" Handler="ComboBoxItemSelected"/>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
</Grid>
</Window>
```
C#代码:
```csharp
using System.Collections.ObjectModel;
using System.Data.SQLite;
using System.Windows;
namespace ComboBoxDemo
{
public partial class MainWindow : Window
{
private ViewModel viewModel;
public MainWindow()
{
InitializeComponent();
viewModel = new ViewModel();
DataContext = viewModel;
}
private void ComboBoxItemSelected(object sender, RoutedEventArgs e)
{
MessageBox.Show($"Selected: {viewModel.SelectedItem}");
}
}
public class ViewModel
{
private ObservableCollection<string> source;
public ViewModel()
{
source = new ObservableCollection<string>();
LoadData();
}
public ObservableCollection<string> Source
{
get { return source; }
set { source = value; }
}
private string selectedItem;
public string SelectedItem
{
get { return selectedItem; }
set { selectedItem = value; }
}
private string text;
public string Text
{
get { return text; }
set
{
text = value;
if (source.IndexOf(text) == -1)
{
source.Add(text);
UpdateData();
}
}
}
private void LoadData()
{
using (SQLiteConnection connection = new SQLiteConnection("Data Source=MSJ.db"))
{
connection.Open();
using (SQLiteCommand command = new SQLiteCommand("SELECT Source FROM Source", connection))
{
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
source.Add(reader.GetString(0));
}
}
}
}
}
private void UpdateData()
{
using (SQLiteConnection connection = new SQLiteConnection("Data Source=MSJ.db"))
{
connection.Open();
using (SQLiteCommand command = new SQLiteCommand("INSERT INTO Source (Source) VALUES (@Source)", connection))
{
command.Parameters.AddWithValue("@Source", text);
command.ExecuteNonQuery();
}
}
}
}
}
```
注意:为了运行上述代码,需要在项目中添加以下文件:MSJ.db、SQLite.Interop.dll、System.Data.SQLite.dll。其中,MSJ.db是SQLite数据库文件,SQLite.Interop.dll和System.Data.SQLite.dll是SQLite的.NET Framework驱动程序。