WPF入門教程系列二十八 ——DataGrid使用示例MVVM模式(5)

WPF入門教程系列五——Window 介紹

 
 

添加ClickAction的實現

      通過上面兩步,我們將準備工具全部做完了,現在需要在.xmal文件中給Button按鈕的Command屬性綁定了一個方法叫做ClickSaveAction,DataGrid控件的SelectItem綁定MainWindowVM(ViewModel)中的AreaVM屬性。

1. 在Visual Studio 2022中打開MainWindows.xmal文件。

2. 對DataGrid的SelectItem進行了數據綁定。具體代碼如下:

 <DataGrid x:Name="gridArea" Grid.Row="1" d:ItemsSource="{d:SampleData ItemCount=5}" 
AutoGenerateColumns
="False"
HorizontalAlignment="Left" VerticalAlignment="Top" SelectedItem="{Binding Path=AreaVM,
Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}
">

3.將ClickSaveCommand綁定到Button按鈕的Command屬性上,這個ClickSaveCommand指令將代替保存按鈕的click事件,將數據保存到數據庫。具體代碼如下:

<Button  x:Name="btnSave" Height="22" Width="120" Command="{Binding ClickSaveAction}" >保存</Button>

注意:Command屬性僅僅作爲Click行爲的綁定,其他行爲,如鼠標移入、移出等事件,要使用另外的MVVM方式進行綁定。

4.MainWindow.xmal的全部代碼如下:

<Window x:Class="WpfGridDemo.NET7.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:WpfGridDemo.NET7"
        mc:Ignorable="d"
        Title="MainWindow" Height="600" Width="960">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="100"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="25"></RowDefinition>
        </Grid.RowDefinitions>

        <DataGrid x:Name="gridArea" Grid.Row="1" d:ItemsSource="{d:SampleData ItemCount=5}" 
AutoGenerateColumns
="False"
HorizontalAlignment
="Left" VerticalAlignment="Top" SelectedItem="{Binding Path=AreaVM, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"> <DataGrid.Columns> <DataGridComboBoxColumn Header="城市" Width="120" x:Name="cboCity"
ClipboardContentBinding
="{x:Null}" SelectedValuePath="Code"
SelectedValueBinding
="{Binding Path=CityCode,UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath
="Name" SelectedItemBinding="{x:Null}" /> <DataGridTextColumn Header="縣區鎮" Width="*" Binding="{Binding Name}"
ClipboardContentBinding
="{x:Null}"/> <DataGridTextColumn Header="郵編" Width="100" Binding="{Binding Code}"
ClipboardContentBinding="{x:Null}"/> <DataGridTextColumn Header="創建時間" Width="160" Binding="{Binding Created}"
ClipboardContentBinding="{x:Null}"/> <DataGridTextColumn Header="更新時間" Width="160" Binding="{Binding Updated}"
ClipboardContentBinding="{x:Null}"/> </DataGrid.Columns> </DataGrid> <WrapPanel Grid.Row="2"> <Button x:Name="btnRefresh" Height="22" Width="120" Click="btnRefresh_Click">刷新</Button> <Button x:Name="btnSave" Height="22" Width="120" Command="{Binding ClickSaveAction}" >保存</Button> </WrapPanel> </Grid> </Window>

5.在Visual Studio 2022中按F5鍵,啓動WPF應用程序,使用鼠標左鍵點擊“刷新”按鈕,在數據呈現之後,使用鼠標左鍵選中DataGrid中的一條記錄,進行修改,然後點擊“保存”按鈕。如下圖。

6. 使用鼠標左鍵點擊“刷新”按鈕,在數據呈現之後,我們發現,剛纔所做的修改,已經保存到數據庫了。如下圖。 

數據已經保存到數據庫,如下圖。

 

7.如果我們要讓保存按鈕禁用,可以將執行的方法返回爲False,具體代碼如下:

        /// <summary>

        /// 命令是否可以執行
        /// </summary>
        /// <returns></returns>
        bool CanSaveExecute()
        {
return false; }

8. 在Visual Studio 2022中按F5鍵,啓動WPF應用程序,能夠看到,界面中按鈕已經是禁用狀態了,我們綁定的這個命令是否可以執行,是直接影響到按鈕能否被點擊的!這個值會直接作用在按鈕的IsEnabled上。如下圖。

 

 

七、ComboBox下拉事件轉爲Command命令

用於 DataGridComboBoxColumn 顯示有一組項可供選擇的數據,例如枚舉。 DataGridComboBoxColumn 允許用戶從下拉列表中選擇項。本文通過將Command命令綁定到comboBox的SelectionChanged事件上,實現自動刷新用戶選擇的省份的相應城市信息。

在WPF中默認的Command綁定往往不能滿足覆蓋所有的事件,例如ComboBox的SelectionChanged事件,DataGrid的SelectionChanged事件等等,這時就可以用到一個擴展庫,來實現事件綁定Command。

微軟從WPF 4.0開始,引入了一個比較實用的庫——Interactions,這個庫主要是通過附加屬性來對UI控件注入一些新的功能,除了內置了一系列比較好用的功能外,還提供了比較良好的擴展接口。

    本文這裏簡單的介紹一下Behavior這個擴展,顧名思義,Behavior可以賦予控件新的行爲能力。

    事件綁定到Command需要用到Interaction.Triggers這個屬性 ,在這個屬性裏面添加一個或多個EventTrigger並指定關注的的事件名稱,在EventTrigger中通過InvokeCommandAction來綁定事件對應的command。

1. 在Visual Studio 2022中打開MainWindows.xmal文件,並在文件的開頭添加如下命名空間。

          xmlns:be="http://schemas.microsoft.com/xaml/behaviors"

2. 在MainWindows.xmal文件中添加一個ComboBox控件,具體代碼如下:

<WrapPanel Grid.Row="0" HorizontalAlignment="Left">
            <ComboBox x:Name="cboProvince" DisplayMemberPath="Name" SelectedValuePath="Code" >
                <be:Interaction.Triggers>

                    <be:EventTrigger EventName="SelectionChanged">
                        <be:InvokeCommandAction Command="{Binding ProviceChangedAction}"/>

                    </be:EventTrigger>
                </be:Interaction.Triggers>
            </ComboBox>
        </WrapPanel>

3.     在寫完了以上代碼之後,Visual Studio 2022的界面設計器中原來呈現的UI界面,消失了,顯示“無效標記,有關詳細信息,請查看錯誤列表”。如下圖。

4.從錯誤信息中來查看,應用程序缺少程序集,沒有安裝相應的程序包。使用鼠標在菜單欄中選擇“工具--》NuGet軟件包管理器- -》 管理此解決方案的NuGet程序包”,如下圖。

5.    在Visual Studio 2022的NuGet-解決方案標籤頁中,瀏覽頁面的搜索框中輸入“Microsoft.Xaml.Behaviors.Wpf”進行搜索,然後使用鼠標左鍵先選中要安裝的項目名稱,然後再點擊“安裝”按鈕。如下圖。

6.安裝成功之後,錯誤列表中的錯誤信息消失了,UI設計器中的UI又回來了。如下圖。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章