我正在使用WPF UI套件的DataGrid。在DataGridTemplateColumn中,我使用了AutoCompleteBox并使用值列表设置其静态资源。我想获取AutoCompleteBox的文本。开始时,我已经使用Item Object绑定了Data Grid空值,以便在AutocompleteBox中进行搜索时,选择一个值并按Enter,然后该值在MessageBox等中显示为输出。
注意:此值将进一步用于从数据库搜索项目。
问题是,按Enter键时AutoCompleteBox值显示为空。
DataGrid:
<DataGrid Name="CartTable" Grid.Row="2" AutoGenerateColumns="False" Margin="20,0" Height="300" GridLinesVisibility="All" CanUserAddRows="True" SelectionChanged="CartTable_SelectionChanged" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="Code" Width="1*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<controls:AutoCompleteBox Text="{Binding Code, Mode=TwoWay}" ItemsSource="{StaticResource ItemList}" IsTextCompletionEnabled="True" PreviewKeyDown="AutoCompleteBox_PreviewKeyDown"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Name" Width="1*" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Description" Width="1*" Binding="{Binding Description}"/>
<DataGridTemplateColumn Header="Quantity" Width="1*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<controls:AutoCompleteBox Text="{Binding Quantity, Mode=TwoWay}" ItemsSource="{StaticResource ItemList}" Name="Quantity"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Unit Price" Width="1*" IsReadOnly="True" Binding="{Binding UnitPrice}"/>
<DataGridTextColumn Header="Sub-Total" Width="1*" IsReadOnly="True" Binding="{Binding SubTotal}"/>
<DataGridTemplateColumn Header="Delete" Width="1*" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Delete" Name="DelBtnGrid" Click="DelBtnGrid_Click"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
静态资源列表:
public class ItemCodeList : List<string>
{
public ItemCodeList()
{
Items(1);
}
void Items(int column)
{
Database database = new Database();
database.DBOpen();
SQLiteDataReader sQLiteDataReader = database.SelectAllOrderBy(Database.TABLE_ITEMS, Database.ID_ITEMS, "DESC");
try
{
this.Clear();
while (sQLiteDataReader.Read())
{
string value = sQLiteDataReader.GetString(column);
this.Add(value);
}
sQLiteDataReader.Close();
database.DBClose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (sQLiteDataReader != null)
{
sQLiteDataReader.Close();
database.DBClose();
}
}
}
SaleTab:
public SaleTab()
{
InitializeComponent();
Item item = new Item()
{=
Code = "",
Name = "",
Description = "",
Quantity = "",
UnitPrice = "",
SubTotal = ""
};
}
AutoCompleteBox_PreviewKeyDown
private void AutoCompleteBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.Enter)
{
AutoCompleteBox x = CartTable.Columns[0].GetCellContent(CartTable.Items[0]) as AutoCompleteBox;
if (x != null)
{
MessageBox.Show(x.Text);
} else
{
MessageBox.Show("null");
}
}
}