当前位置:网站首页>20. MVVM command binding of WPF
20. MVVM command binding of WPF
2022-06-25 12:09:00 【komla168】
Preface :Command It can effectively reduce the coupling between the front end and the rear end , It is conducive to code management and readability . Front end control Command Sometimes it's possible to simply execute a function , such as Button. But with the help of events Command Realization MVVM Mode control , It needs to pass Command take EventArgs The relevant information in is transmitted to ViewModel To parse the operation . All in all , because MVVM The pattern of ,ViewModel You can't get it easily View Data of the control in , Especially the event information .
clear :WPF Data driven instead of traditional event driven .
The goal is :MVVM In mode , Can be like MVC equally , It can realize the separation of front and back end data , It's like View The background program is as easy and View Controls in the .
I use Prism To achieve Command, No longer make your own wheels ,Prism Version of >=8.0
To achieve the goal , There are two things , One is command , One is binding . Binding is the foundation , Command is the means to achieve a goal .
One 、 No parameter command
This is simpler , Generally used to demonstrate basic usage . We use Button To test , Although with Button Not representative ( It's so special , Bring their own Commad This attribute ), But this simple operation is not affected .
<StackPanel VerticalAlignment="Center">
<TextBox Width="120" Height="30" Text="{Binding NameText}"></TextBox>
<Button Width="120" Height="30" Command="{Binding ButtonCommand}"> Button </Button>
</StackPanel>
backstage
private DelegateCommand buttonCommand;
public DelegateCommand ButtonCommand =>
buttonCommand ?? (buttonCommand = new DelegateCommand(BtnCmd));
void BtnCmd() { }It's simple , Click the button on the front end , Activate this command , Then execute the method in the command BtnCmd();
Two 、 Command with parameters
2.1 demand
Only inherited ICommandSource Interface controls will have Command Dependency property , Basically only ButtonBase and MenuItem Inherited ICommandSource, So it's like Button、RadioButton、CheckBox There are Command attribute , But some of our common TextBox、ComboBox Wait, No Command attribute .
2.2 Demand for logic
1、View The data and changes of some integrated controls in MVVM Cannot be in mode ViewModel know , such as DataGrid、ComBox、DatePicker Wait for the mouse of the control and the event of selection change .
2、 The events of these controls cannot be bound to ViewModel in , It can only be realized through event to command MVVM Pattern ;
3、 There is... In the event EventArgs Parameters , This parameter is very important , With some event data information , And that's what we want EventArgs With data information , What else would we do to trigger this event !
This is often used in development .
2.3 System.Windows.Controls.Primitives.CommandParameter

This is a ButtonBase Medium CommandParameter attribute , If using Microsoft.Xaml.Behaviors In the assembly Interaction Implemented events are transferred to Command, This CommandParameter Is in Microsoft.Xaml.Behaviors Under the namespace , There is no difference in its usage .

Let's use it first Button Medium CommandParameter To measure .
<ComboBox Name="cmb" Width="100" Height="40" HorizontalAlignment="Left">
<ComboBoxItem Content=" One " FontSize="18"/>
<ComboBoxItem Content=" Two " FontSize="18"/>
<ComboBoxItem Content=" 3、 ... and " FontSize="18"/>
<ComboBoxItem Content=" Four " FontSize="18"/>
<ComboBoxItem Content=" 5、 ... and " FontSize="18"/>
<ComboBoxItem Content=" 6、 ... and " FontSize="18"/>
</ComboBox>
<Button Command="{Binding ButtonCommand}" CommandParameter="{Binding ElementName=cmb, Path=SelectedIndex}"/>ViewModel
private DelegateCommand<int> buttonCommand;
public DelegateCommand<int> ButtonCommand =>
buttonCommand ?? (buttonCommand = new DelegateCommand<int>(BtnCmd));
void BtnCmd(int selValue)
{
MessageBox.Show(selValue.ToString());
}
pit 1:

That is to say DelegateCommand<T>, This T Not a object It's not a NUllable, Here are the knowledge points related to data types .
ask :Int Belong to Object Do you ?
answer : Do not belong to

Int Value type , and Object Is a reference type . hold DelegateCommand<T> Medium T Switch to string No problem .
I'll change it here , take Int Switch to Object, That's all right. .

Through here CommandParameter The binding ComboBox The control of SelectedIndex attribute , Then the background needs to use DelegateCommand Generic functions of , You can also see the generic above , Need to be Object Type of . Finally, the function executed by this command also needs parameters , This is like an event function , The difference is , The event function usually has two parameters , One is sender, One is EventArgs( Or other event parameters ), You need to operate on these two parameters , Extract what we need from it , But here , We do it by binding , We have clearly known what data in the event parameters we want , You can directly manipulate the data passed in through the binding . One is to extract the required parameters in the background , One is to write the required parameters in the front end and pass them to the background .
2.4 Microsoft.Xaml.Behaviors. CommandParameter
Use the same method as above , Through here Interaction To achieve Command. Use HandyControl Medium DatePicker Control demo .
<hc:DatePicker x:Name="startDpEventDate" ShowClearButton="True" Margin="2"
SelectedDate="{x:Static system:DateTime.Now}"
Width="230" Height="40"
hc:InfoElement.TitleWidth="85"
hc:InfoElement.TitlePlacement="Left"
hc:InfoElement.Title=" Starting time "
FontSize="18">
<bh:Interaction.Triggers>
<bh:EventTrigger EventName="SelectedDateChanged">
<bh:InvokeCommandAction Command="{Binding StartDatePickerCmd}"
CommandParameter="{Binding ElementName=startDpEventDate, Path=SelectedDate}"/>
</bh:EventTrigger>
</bh:Interaction.Triggers>
</hc:DatePicker>The backstage is similar to the last one , The difference is the operation for different properties of different controls . The bound control here is its own ( There are other ways ,Binding Knowledge about , See references 3.7 It's useful to ), The attribute is SelectedDate.
void StartDatePicker(object startTime)
{
string s = startTime.ToString();
MessageBox.Show(s);
}Empathy , Other controls such as DataGrid, This method can be used to select and change events MVVM operation .
Of course , You can also write multiple commands at the same time , See references 3.3. At the same time, by modifying the data template of the list control , You can implement the list control item Term Command function , See references 3.4.

3、 ... and 、 Citations
3.1 Wpf MVVM—— Command binding and message sending _weixin_44538156 The blog of -CSDN Blog
3.2 Customize InvokeMouseCommandAction class , be used for WPF Mouse events in to prism:DelegateCommand The binding of _jiuzaizuotian2014 The blog of -CSDN Blog
3.3 MVVM Easy to achieve Command binding ( 3、 ... and ) Of any event Command - cw_volcano - Blog Garden
边栏推荐
- Application of analytic hierarchy process in college teaching evaluation system (principle + example + tool)
- confluence7.4. X upgrade record
- R语言使用构建有序多分类逻辑回归模型、epiDisplay包的ordinal.or.display函数获取有序logistic回归模型的汇总统计信息(变量对应的优势比及其置信区间、以及假设检验的p值)
- Kotlin学习笔记
- VFP uses Kodak controls to control the scanner to solve the problem that the volume of exported files is too large
- How to use ARIMA model for prediction?
- 一個硬件工程師走過的彎路
- 做自媒体视频需要怎么做才能年收入一百万?
- 依概率收敛
- 图片打标签之获取图片在ImageView中的坐标
猜你喜欢

The service layer reports an error. The XXX method invalid bound statement (not found) cannot be found

Database Series: MySQL index optimization summary (comprehensive version)

Black Horse Chang Shopping Mall - - - 3. Gestion des produits de base
![Caused by: org. xml. sax. SAXParseException; lineNumber: 1; columnNumber: 10; Processing matching '[xx][mm][ll]' is not allowed](/img/27/ebf13bdb16978bedbeaa5cd1d780c9.jpg)
Caused by: org. xml. sax. SAXParseException; lineNumber: 1; columnNumber: 10; Processing matching '[xx][mm][ll]' is not allowed

Continue to cut the picture after the ArcGIS Server is disconnected

How terrible is it not to use error handling in VFP?

flutter常用命令及问题

15. Notes on the button style of WPF

黑马畅购商城---6.品牌、规格统计、条件筛选、分页排序、高亮显示

Using DBF of VFP to web salary query system
随机推荐
Dark horse shopping mall ---6 Brand, specification statistics, condition filtering, paging sorting, highlighting
架构师为你揭秘在阿里、腾讯、美团工作的区别
文献之有效阅读
Sword finger offer II 091 Painting house: application of state machine DP
The idea of mass distribution of GIS projects
Continue to cut the picture after the ArcGIS Server is disconnected
The latest IT learning route in 2020
R语言dplyr包summarise_at函数计算dataframe数据中多个数据列(通过向量指定)的计数个数、均值和中位数、在每个函数内部指定na.rm参数、通过list指定函数列表
WebRTC Native M96 基础Base模块介绍之实用方法的封装(MD5、Base64、时间、随机数)
机器学习自学成才的十条戒律
R语言使用构建有序多分类逻辑回归模型、epiDisplay包的ordinal.or.display函数获取有序logistic回归模型的汇总统计信息(变量对应的优势比及其置信区间、以及假设检验的p值)
Idea local launch Flink task
揭秘GaussDB(for Redis):全面对比Codis
RecyclerView滚动到指定位置
What are redis avalanche, penetration and breakdown?
How to open an account for trading futures Shanghai nickel products online
The service layer reports an error. The XXX method invalid bound statement (not found) cannot be found
VFP function to summarize all numeric columns of grid to cursor
[regression analysis] understand ridge regression with case teaching
Actual combat summary of Youpin e-commerce 3.0 micro Service Mall project