简体   繁体   中英

How to add different type of controls dynamically on a stackpanel C# WP8

I want to add an Image and a MediaElement in a stackpanel from my C# code dynamically, but i cant see the other elements, so in my xaml code i have this:

<ListBox x:Name="lstbxUIElements" Width="auto" Height="auto">
    <ListBox.ItemsPanel>
         <ItemsPanelTemplate>
             <StackPanel Name="stackContainer" DataContext="{Binding}" Orientation="Horizontal"/>
         </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

in my C# code the user can take a photo or a video, and I want to show them in the stackpanel horizontally, i just can see one element. my C# code:

//Constructor
public MainPage()
{
    lstbxUIElements.ItemsSource = multiMediaElements;//(List<Objects> multiMediaElements)
}

public void MethodVideo()
{
    MediaElement a ="some code to retrieve mp4"
    multiMediaElements.add(a);
}

public void MethodImage()
{
    BitmapImage bmp = new BitmapImage();
    bmp.SetSource(e.ChosenPhoto);
    multiMediaElements.add(bmp);
}

any suggestion? (working with WP8)

Use the right control for the right task. If you want to add controls to your panel, you don't need a listbox, use directly the stackpanel instead:

<StackPanel Name="UIElements" Orientation="Horizontal"/>

Then use the Children property to add your controls:

public void MethodImage()
{
    BitmapImage bmp = new BitmapImage();
    bmp.SetSource(e.ChosenPhoto);
    UIElements.Children.Add(bmp);
}

If you need to add controls in the listbox then directly add it you don't need to define any item template and then do the usual binding. you can do as shown in below code:

XAML:

<ListBox x:Name="lstbxUIElements" Width="auto" Height="auto" />

C#

BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
lstbxUIElements.Items.Add(bmp)

For multiple items keep on adding the element in the listbox items as shown above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM