当前位置:网站首页>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

3.4 WPF: stay MVVM In the design, the realization of ListViewItem Double click the response to the event - WPInfo - Blog Garden

3.5 Prism8.0( Two ): Data binding and command _ A quiet blog read in pieces -CSDN Blog _prism Attribute binding

3.6 Introduction to Prism | Prism

3.7 wpf How to pass parameters through CommandParameter Pass in viewmodel_ Old program ape a blog -CSDN Blog  

原网站

版权声明
本文为[komla168]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251155069150.html