gpt4 book ai didi

c# - 在后面创建数据模板代码

转载 作者:行者123 更新时间:2023-11-30 13:27:09 24 4
gpt4 key购买 nike

我正在尝试为显示数据创建一个 ListBox View ,我希望它包含一个带有 2 列“Product ID & Product Barcode”数据模板的 ListBox

我想使用纯 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;
}

但是没有数据出现,请指教。谢谢,

最佳答案

如果它定义了 x:Key,您可以在 xaml 中定义资源并在代码隐藏中检索它。

在你的 xaml 中:

<DataTemplate x:Key="anyId">...</DataTemplate>

在你后面的代码中:

var dataTemplate = Application.Current.TryFindResource("anyId") as DataTemplate;

var dataTemplate = Application.Current.FindResource("anyId") as DataTemplate;

关于c# - 在后面创建数据模板代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14053804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com