21.3.1 实现更新模式(2)
2. 修改按钮标签
可以给视图类添加一个控件数据成员m_EditOrderCtrl,从而得到对应于Edit Order按钮的对象;添加方法与为编辑控件添加变量的方法完全相同。该变量的类型是CButton-- 这是定义按钮的MFC类。可以使用该变量,调用CButton类中从CWnd继承的SetWindowText()成员,从而设置按钮标签:
- void COrderDetailsView::OnEditorder()
- {
- if(m_Mode == UPDATE)
- { // When button was clicked we were in update
- // Disable input to edit controls
- m_QuantityCtrl.SetReadOnly();
- m_DiscountCtrl.SetReadOnly();
-
- // Change the Update button text to Edit Order
- m_EditOrderCtrl.SetWindowText(_T("Edit Order"));
-
- // Make the Cancel button invisible
- // Enable Record menu items and toolbar buttons
- // Complete the update
- m_Mode = READ_ONLY; // Change to read-only mode
- }
- else
- { // When button was clicked we were in read-only mode
-
- // Enable input to edit controls
- m_QuantityCtrl.SetReadOnly(FALSE);
- m_DiscountCtrl.SetReadOnly(FALSE);
-
- // Change the Edit Order button text to Update
- m_EditOrderCtrl.SetWindowText(_T("Update"));
-
- // Make the Cancel button visible
- // Disable Record menu items and toolbar buttons
- // Start the update
- m_Mode = UPDATE; // Switch to update mode
- }
- }
每次调用SetWindowText()函数,都会将按钮上显示的文本设置为给该函数提供的实参字符串。形参的类型是LPCTSTR,可以给它提供CString类型的实参或_T类型的字符串常量。
3. 控制Cancel按钮的可见性
为了使Cancel按钮可见或不可见,需要使用某个对应于该按钮的控件变量,因此就像前面为Edit Order按钮添加变量那样,添加一个名为m_CancelEditCtrl的控件变量。因为CButton类是从CWnd类派生的,所以可以调用CButton对象中继承的ShowWindow()成员,将该按钮设定为可见或不可见,相应的代码如下所示:
- void COrderDetailsView::OnEditorder()
- {
- if(m_Mode == UPDATE)
- { // When button was clicked we were in update
- // Disable input to edit controls
- m_QuantityCtrl.SetReadOnly();
- m_DiscountCtrl.SetReadOnly();
-
- // Change the Edit Order button text to Update
- m_EditOrderCtrl.SetWindowText(_T("Edit Order"));
-
- // Make the Cancel button invisible
- m_CancelEditCtrl.ShowWindow(SW_HIDE);
-
- // Enable Record menu items and toolbar buttons
- // Complete the update
- m_Mode = READ_ONLY; // Change to read-only mode
- }
- else
- { // When button was clicked we were in read-only mode
-
- // Enable input to edit controls
- m_QuantityCtrl.SetReadOnly(FALSE);
- m_DiscountCtrl.SetReadOnly(FALSE);
-
- // Change the Edit Order button text to Update
- m_EditOrderCtrl.SetWindowText(_T("Update"));
-
- // Make the Cancel button visible
- m_CancelEditCtrl.ShowWindow(SW_SHOW);
-
- // Disable Record menu items and toolbar buttons
- // Start the update
- m_Mode = UPDATE; // Switch to update mode
- }
- }
CButton类从CWnd继承的ShowWindow()函数要求实参是int类型,还必须是一组固定值中的一个(参见文档了解完整的数值集)。如果m_Mode的值是UPDATE,我们就使用实参值SW_HIDE使该按钮消失;当应用程序进入编辑模式时,我们使用实参值SW_SHOW使该按钮可见,并将其激活。