如何从XAML中定义的数据模板以编程方式创建元素?

时间:2013-12-15 03:56:08

标签: c# wpf xaml windows-phone-8 visual-studio-2013

我正在尝试使用下面的文本创建多个按钮,并在运行时将它们添加到代码中的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>

我尝试过像上面那样使用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控件模板来使其工作。有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

在WPF中的过程代码中创建或操作UI元素几乎是never正确的方法。

有些例外情况会有用,但是你提出的这种情况是ItemsControl最简单的情况。

<ItemsControl ItemsSource="{Binding ItemList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Click="Button_OnClick">
                <Button.Template>
                    <ControlTemplate 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>
                </Button.Template>
            </Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

代码背后:

    private void Button_OnClick(object sender, RoutedEventArgs e)
    {
        var button = sender as Button;
        var dataitem = button.DataContext as [YourItemclass];

        //... here you can perform actions on the dataitem.
    }
  • 使用ItemsControl,您的让WPF为每个项目创建UI,而不是自己创建。
  • 每个Button的DataContext也将由WPF设置为基础集合中的相应数据项。
  • 无需诉诸使用Tag财产或类似内容的可怕黑客。
  • StackPanelItemsControl的默认ItemsPanel,但您可以通过设置ItemsPanel将其更改为其他面板(例如WrapPanel

答案 1 :(得分:1)

您可以使用XamlReader创建包含动态内容的xaml。这样,您就可以在运行时设置任何属性。

http://msdn.microsoft.com/en-us/library/system.windows.markup.xamlreader(v=vs.110).aspx