簡體   English   中英

如何從XAML中定義的數據模板以編程方式創建元素?

[英]How do you create an element programmatically from a data template defined in XAML?

我正在嘗試使用下面的文本創建多個按鈕,並在運行時將它們添加到代碼中的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控件模板來使其工作。 有什么想法嗎?

謝謝!

在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

您可以使用XamlReader創建具有動態內容的xaml。 這樣,您就可以在運行時設置任何屬性。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM