我正在尝试创建一个 ListBox 视图来显示数据,并且我希望它包含一个带有 datatemplate 的 ListBox,用于显示两列“产品 ID 和产品条形码”。
我想要使用纯 C# 代码创建它,或者如果可能的话,通过 xaml 加载它? 如果我可以创建一个模板,我可以将其作为某种资源在 c# 中获取。
目前我所做的是: 在 XAML 中:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="37*" />
<RowDefinition Height="88*" />
</Grid.RowDefinitions>
<TextBlock Text="Type Your Search :" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="112" Height="15.96" Margin="20,0,0,4" />
<TextBox HorizontalAlignment="Right" VerticalAlignment="Bottom" Height="25" Width="300" Margin="0,0,44,0" x:Name="txtCAuto" TextWrapping="NoWrap" HorizontalContentAlignment="Right" />
<ListBox x:Name="lbSuggestion" SelectionChanged="lbSuggestion_SelectionChanged" Foreground="Black" Width="300" Margin="0,0,44,0" FlowDirection="RightToLeft" Background="LightYellow" Grid.Row="1" Visibility="Collapsed" ScrollViewer.HorizontalScrollBarVisibility="Auto" ItemsSource="{Binding}" HorizontalAlignment="Right" VerticalAlignment="Top" HorizontalContentAlignment="Right" BorderBrush="Transparent" Grid.IsSharedSizeScope="True">
</ListBox>
</Grid>
在代码后台:
string typedString = txtCAuto.Text.ToUpper();
List<string> autoList = new List<string>();
autoList.Clear();
prodDetails ps = SelProd4Sale();
foreach (string item in ps.ProdBrcdList)
{
if (!string.IsNullOrEmpty(txtCAuto.Text))
{
if (item.StartsWith(typedString))
{
//autoList.Add(item);
FrameworkElementFactory colProdID = new FrameworkElementFactory(typeof(TextBlock));
Binding prodID = new Binding(ps.ProdIDList.ToString());
colProdID.SetBinding(TextBlock.TextProperty, prodID);
FrameworkElementFactory colProdBarcode = new FrameworkElementFactory(typeof(TextBlock));
Binding prodBarcode = new Binding();
prodBarcode.Path = new PropertyPath(ps.ProdBrcdList.ToString());
colProdBarcode.SetBinding(TextBlock.TextProperty, prodBarcode);
FrameworkElementFactory sb = new FrameworkElementFactory(typeof(StackPanel));
sb.AppendChild(colProdID);
sb.AppendChild(colProdBarcode);
dTemplate = new DataTemplate { VisualTree = sb };
dTemplate.Seal();
}
}
}
if (autoList.Count > 0)
{
lbSuggestion.ItemTemplate = dTemplate;
//lbSuggestion.ItemsSource = autoList;
lbSuggestion.Visibility = Visibility.Visible;
}
else if (txtCAuto.Text.Equals(""))
{
lbSuggestion.Visibility = Visibility.Collapsed;
lbSuggestion.ItemsSource = null;
}
else
{
lbSuggestion.Visibility = Visibility.Collapsed;
lbSuggestion.ItemsSource = null;
}
但是没有数据出现,请问有什么建议吗? 谢谢。
ListBoxItem
? - sa_ddam213