简体   繁体   中英

C# .NET dynamic form controls or wpf templates

In a WPF application, I would like to display a grid of tiles (buttons essentially) using images from a folder location. There could be any different number of images in the folder, so the tiles/buttons need to be generated dynamically and formatted based on the amount. These need to be buttons that can trigger mouse click events.

I'm very new to C# and .NET, so I'd just like some direction on what the best way of doing this would be. I've started this as a WPF application so would using a template be a good idea? Or if just dynamically creating form buttons with background images is an easy option then I'll give that a go.

You would probably need a ItemsControl such as a ListView. Unfortunately WPF only ships the GridView implementation, but the ListView was intended to support all those views you see in the Windows file explorer. For a Tiled based view you would need to override the ViewBase class and assign it to the View property of the ListView.

Years ago I have had sample code that demonstrated what you want.

The following link contains MSDN samples: MSDN ListView.View samples

How to: Create a Custom View Mode

I know that the Xceed DataGrid has a built-in CardView mode. I don't know if it is available in the free version: Xceed WPF DataGrid documentation

Edit I just checked the MSDN samples and I think they are close to what you want.

I would go for ItemsControl . You need a class representing your buttons, with properties such as X, Y, ImageUri, and so on. You expose your generated buttons via ObservableCollection and bind it to ItemsSource of your ItemsControl . Then you change your ItemsPanelTemplate to grid:

        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Grid>                        
                    <!--Here go rows and columns definitions-->
                </Grid>
            </ItemsPanelTemplate>                
        </ItemsControl.ItemsPanel>

If you have fixed number of rows and columns, you may add them directly in XAML, otherwise generate them at runtime in code-behind. You add ItemsContainerStyle for positioning:

        <ItemsControl.ItemContainerStyle>
            <Style>
                <Setter Property="Grid.Row" Value="{Binding Y}" />
                <Setter Property="Grid.Column" Value="{Binding X}" />
            </Style>
        </ItemsControl.ItemContainerStyle>

Also, you need ItemTemplate which will cover displaying button with image. Other options would be to use Canvas or UniformGrid as ItemsPanelTemplate (both with their advantages and disadvantages).

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