We help IT Professionals succeed at work.

Display Custom WPF User Control using Code

Medium Priority
1,968 Views
Last Modified: 2013-11-12
Hi to all,

I am working on a WPF application that load Items from my database into a WPF Listview in a Gridview View. I have a Checkbox next to each loaded item. When the checkbox is checked I want to display a custom user control, but for the life of me can't figure out how to do that. The fact that I have been working 2 days straight on this might have to do with it and I would really appreciate any help with this. I can't load the user control for each Item (I think), because there is a minimum of 500 Items. This must be done by code.

Thanks for the help
Comment
Watch Question

1. You'll need to handle a OnChange event for the check boxes.
2. Create a new instance of the WPF user control
3. Add it to an appropriate container.

Unfortunately, xaml can't be uploaded to the site, so here's my sample project:


Window1.xaml.vb
Class Window1 
    Private Sub CheckBox1_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles CheckBox1.Checked
        Dim uc As New TestControl
        StackPanel1.Children.Add(uc)
    End Sub
End Class
 
-- Window1.xaml
<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <CheckBox Margin="0,0,0,0" Name="CheckBox1" Grid.Row="0">Check me to add a user control</CheckBox>
        <StackPanel Name="StackPanel1" Grid.Row="1"></StackPanel>
    </Grid>
</Window>
 
-- TestControl.xaml
<UserControl x:Class="TestControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="200" Height="200">
    <Rectangle Height="200" Name="Rectangle1" Stroke="Black" Fill="LimeGreen" Width="200" />
</UserControl>

Open in new window

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
Thanks Chaosian, this helped me find my answer.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.