当前位置:网站首页>C WPF realizes dynamic loading of controls through binding
C WPF realizes dynamic loading of controls through binding
2022-06-23 07:28:00 【CodeOfCC】
List of articles
Preface
Use wpf Development sometimes requires dynamic loading of controls , Write directly in the background cs Code , The styles will be hard to write and less readable , At this time, we need to find a way to completely xaml Defines the styles of dynamically loaded controls in , Although we can define templates in the resource dictionary , Then get the template in the background and add it to the interface , But this process is still very troublesome and has nothing to do with mvvm Are not compatible . A better approach would be to use ItemsControl,ItemsControl As ListBox The usage of the ancestor class of is basically the same , We can customize its internal layout , And element templates , The dynamic loading of controls can be realized by binding data sources ,cs The client does not need to process any interface code .
One 、 How to achieve ?
1、 Use ItemsControl
as everyone knows ListBox As a list control, you can dynamically load elements , and ItemsControl Is its ancestor , We can use it to dynamically load elements . Or directly ListBox Yes, but there may be more attributes to set , For example, remove the element focus box , Element default margins , Remove borders, etc .
<ItemsControl/>
2、 Setting up layout
We set the layout we need according to the usage scenario , Set up ItemsControl Of ItemsPanel that will do .
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid></Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
3、 Define control templates
adopt ItemsControl Of ItemTemplate To set the target that we need to dynamically load the control . And you can select different templates through triggers , For example, this method can be used to realize the dynamic loading of whiteboard controls .
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="ok" />
</DataTemplate>
</ItemsControl.ItemTemplate>
4、 Bind data source
and ListBox similar , Use ItemsSource Just bind the entity .
<ItemsControl ItemsSource="{Binding lst}" />
Two 、 Examples of use
1. Dynamically load shapes
xaml
<Window x:Class="WpfApp2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp2" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800">
<Grid>
<ItemsControl ItemsSource="{Binding Shapes}" Height="450" Width="800">
<ItemsControl.ItemsPanel>
<!-- Layout -->
<ItemsPanelTemplate>
<Grid ></Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!-- Control templates -->
<ItemsControl.ItemTemplate>
<DataTemplate>
<Control x:Name="ctrl" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="{Binding Margin}" Width="{Binding Width}" Height="{Binding Height}" ></Control>
<DataTemplate.Triggers>
<!-- Select different templates according to different types -->
<DataTrigger Binding="{Binding Type}" Value="0">
<!-- rectangular -->
<Setter Property="Template" TargetName="ctrl">
<Setter.Value>
<ControlTemplate >
<Rectangle Fill="RoyalBlue" RadiusX="10" RadiusY="10" Width="{Binding Width}" Height="{Binding Height}"></Rectangle>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Type}" Value="1">
<!-- The ellipse -->
<Setter Property="Template" TargetName="ctrl">
<Setter.Value>
<ControlTemplate >
<Ellipse Fill="GreenYellow" Width="{Binding Width}" Height="{Binding Height}"></Ellipse>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
cs
using System.Collections.Generic;
using System.Windows;
namespace WpfApp2
{
// Shape entity
public class Shape
{
public int Type {
set; get; }
public Thickness Margin {
set; get; }
public double Width {
set; get; }
public double Height {
set; get; }
}
public partial class MainWindow : Window
{
public List<Shape> Shapes {
set; get; } = new List<Shape>();
public MainWindow()
{
InitializeComponent();
Shapes.Add(new Shape() {
Type = 0, Margin=new Thickness(10,10,0,0), Width = 200, Height = 100 });
Shapes.Add(new Shape() {
Type = 0, Margin = new Thickness(300, 22 , 0, 0), Width = 280, Height = 120 });
Shapes.Add(new Shape() {
Type = 1, Margin = new Thickness(33, 255, 0, 0), Width = 200, Height = 100 });
Shapes.Add(new Shape() {
Type = 1, Margin = new Thickness(350, 150, 0, 0), Width = 200, Height = 200 });
DataContext = this;
}
}
}
Results the preview 
summary
for example : That's what we're going to talk about today , This article only introduces the methods , It solves the problem of interface separation , Especially in mvvm In mode , Dynamic loading of any control can be completed only by binding the entity collection . The use of ItemsControl And ListBox The usage is basically the same , Easy to understand and use .
边栏推荐
- Feelm joined the Carbon Disclosure Project as an initiative of Smallville to deal with climate change emergencies
- 313. super ugly number
- 897. incremental sequential search tree
- 异构交易场景交互流程及一致性保证
- In depth learning series 47:stylegan summary
- yolov5检测小目标(附源码)
- Yan's DP analysis
- Flannel 工作原理
- 滚动播报效果的实现
- Paddle version problem
猜你喜欢

GINet

Yan's DP analysis

Principle of skip table

JUnit unit test reports an error org junit. runners. model. InvalidTestClassError: Invalid test class ‘xxx‘ . No runnable meth

TensorFlow中的数据类型

MYSQL牛客刷题

MySQL (11) - sorting out MySQL interview questions

Product axure9 (English version), prototype design and production pull-down secondary menu

U-Net: Convolutional Networks for Biomedical Image Segmentation

In depth learning series 46: face image super score gfp-gan
随机推荐
MySQL (11) - sorting out MySQL interview questions
MySQL(四) — MySQL存储引擎
[AI practice] xgb Xgbregression multioutputregressor parameter 2 (GPU training model)
406 double pointer (27. remove elements, 977. square of ordered array, 15. sum of three numbers, 18. sum of four numbers)
Paddle version problem
[game theory] basic knowledge
Advanced drawing skills of Excel lecture 100 (VIII) -excel drawing WiFi diagram
【博弈论】基础知识
Akamai-1.75版本-_abck参数生成-js逆向分析
leetcode210. Schedule II 207 Curriculum topology sorting DFS BFS
GINet
Redis setting password
codeforce 158B Taxi
Spock sub piling
In depth learning series 46: face image super score gfp-gan
About SQL: is there a way to fill in the null value in the field without adding fields on the basis of the original fields
Nacos适配oracle11g-建表ddl语句
Mysql(十一) — MySQL面试题整理
Spock-sub打桩
20bn Jester complete dataset Download