当前位置:网站首页>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
边栏推荐
- Which securities company's account is better and safer to open
- Mui scroll bar recovery
- Uncover gaussdb (for redis): comprehensive comparison of CODIS
- 数据库系列:MySQL索引优化总结(综合版)
- Why should Apple change objc_ Type declaration for msgsend
- If you also want to be we media, you might as well listen to Da Zhou's advice
- Dark horse shopping mall ---1 Project introduction - environment construction
- Use PHP script to view the opened extensions
- R语言使用构建有序多分类逻辑回归模型、epiDisplay包的ordinal.or.display函数获取有序logistic回归模型的汇总统计信息(变量对应的优势比及其置信区间、以及假设检验的p值)
- Tool usage summary
猜你喜欢
黑馬暢購商城---3.商品管理
SDN系统方法 | 9. 接入网
Two ways of redis persistence -- detailed explanation of RDB and AOF
ROS 笔记(06)— 话题消息的定义和使用
Develop two modes of BS mode verification code with VFP to make your website more secure
Eureka accesses the console and reports an error: whitelabel error page
Caused by: org. xml. sax. SAXParseException; lineNumber: 1; columnNumber: 10; Processing matching '[xx][mm][ll]' is not allowed
架构师为你揭秘在阿里、腾讯、美团工作的区别
Dark horse shopping mall ---1 Project introduction - environment construction
ROS notes (06) - definition and use of topic messages
随机推荐
Problems encountered using easyexcel
Explanation of ideas and sharing of pre-processing procedures for 2021 US game D (with pre-processing data code)
WebRTC Native M96 基础Base模块介绍之网络相关的封装
Two ways of redis persistence -- detailed explanation of RDB and AOF
一個硬件工程師走過的彎路
If you also want to be we media, you might as well listen to Da Zhou's advice
Database Series: MySQL index optimization summary (comprehensive version)
Windows11 MySQL service is missing
【数据中台】数据中台的OneID是个什么鬼,主数据它不香吗?
Deeply understand Flink SQL execution process based on flink1.12
flutter常用命令及问题
The cloud native data lake has passed the evaluation and certification of the ICT Institute with its storage, computing, data management and other capabilities
JS indexof() always returns -1
文献之有效阅读
为什么ping不通网站 但是却可以访问该网站?
How to open an account for trading futures Shanghai nickel products online
Le détour d'un ingénieur en matériel
R语言dplyr包filter函数过滤dataframe数据中指定数据列的内容不是(不等于指定向量中的其中一个)指定列表中的数据行
Mpai data science platform random forest classification \ explanation of regression parameter adjustment
Gradle知识点