我将为您翻译以下内容:
我正在尝试在运行时使用代码创建多个带有文本的按钮,并将它们添加到Stackpanel中。我根据数据列表创建这些按钮。以下是我的代码:
XAML
<StackPanel x:Name="MainSP" />
C#
foreach (item in ItemList)
{
Button newBtn = new Button();
Image buttonImage = new Image();
buttonImage.Width = 100;
buttonImage.Height = 100;
buttonImage.Stretch = Systems.Windows.Media.Stretch.Uniform;
buttonImage.Source = new BitmapImage(pokemon.ImageURI);
newBtn.Tag = item.Id;
newBtn.Name = String.Format("{0}Button", item.Name);
newBtn.Click += new RoutedEventHandler(newBtn_Click);
FamilyStackPanel.Children.Add(newBtn);
}
我知道这是笨拙的编程方式。我真的想在XAML中设置一个ControlTemplate,然后在代码中创建按钮时重复使用它。以下是XAML:
<ControlTemplate x:Key="ButtomTemplate" TargetType="Button">
<Grid Height="108" Width="Auto" Margin = "6,6">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Image Width = "54" Height="54" Stretch="UniformToFill" Grid.Row="0">
<Image.Source>
<BitmapImage UriSource="{Binding ImageUri}" CreateOptions="BackgroundCreation"/>
</Image.Source>
</Image>
<TextBlock Text="{Binding Name}"
Foreground ="{StaticResource PhoneAccentBrush}" />
</Grid>
</ControlTemplate>
我尝试使用像上面那样的控件模板,然后在绑定方面,我在代码中设置了newbtn.DataContext。
foreach (Families item in ItemList)
{
Button newBtn = new Button();
newBtn.Template = this.Resources["ButtonTemplate"] as ControlTemplate;
newBtn.Tag = item.Id;
newBtn.Name = String.Format("{0}Button", item.Name);
newBtn.Click += new RoutedEventHandler(newBtn_Click);
newBtn.DataContext = item;
FamilyStackPanel.Children.Add(newBtn);
}
对于数据上下文,我也尝试过 newBtn.DataContext = ItemList[itemIndex]
,但似乎没有起作用。我只得到了一个空屏幕。
所以我通过纯代码创建按钮来解决了这个问题,但我正在尝试使用XAML控件模板使其工作。你有什么想法吗?
谢谢!