SilverLight学习笔记--实际应用(一)(8):手把手建立一个Silverlight应用程序之应用自定义TextBox控件...

   本步很简单,就是在年龄输入栏中引入我们自定义的TextBox控件,使得此栏在录入数字时只接受正整数,如果用户想键入其它字符则TextBox不接受。这样就减轻了数据校验的压力,多了一层防护。
   控件的创建我们在这里不再重复,请参见SilverLight学习笔记--利用DependencyProperty依赖属性创建自备录入过滤功能的TextBox控件
   我们需要做的就是在项目SLApplicationDataTest中引入我们创建的自定义控件,如图:
                         
修改我们的Page.xaml文件,在头部引入:

 xmlns:mytxtbxsrc = " clr-namespace:SLFilterTextBox;assembly=SLFilterTextBox "

找到Age段,改为:

  < data:DataGridTemplateColumn Header = " Age " >
                    
< data:DataGridTemplateColumn.CellTemplate  >
                        
< DataTemplate >
                                
< Border Background = " {Binding Validator.InvalidAge, Converter={StaticResource myBrushConvert}} "
                                        ToolTipService.ToolTip
= " {Binding Path=Validator, Converter={StaticResource myErrMsgConvert}, ConverterParameter=Age} " >
                                    
< TextBlock  Text = " {Binding Age} " ></ TextBlock >
                                
</ Border >
                        
</ DataTemplate >
                    
</ data:DataGridTemplateColumn.CellTemplate >
                    
< data:DataGridTemplateColumn.CellEditingTemplate >
                        
< DataTemplate >
                                
< mytxtbxsrc:MyFilterTextBox x:Name = " myFilterTBAge "  Text = " {Binding Age , Mode=TwoWay, NotifyOnValidationError=True,  ValidatesOnExceptions=True} "
                                     Background
= " {Binding Validator.InvalidAge, Converter={StaticResource myBrushConvert}} "
                                                             Loaded
= " myFilterTBAge_Loaded " >
                                
</ mytxtbxsrc:MyFilterTextBox >
                            
</ DataTemplate >
                    
</ data:DataGridTemplateColumn.CellEditingTemplate >
 
</ data:DataGridTemplateColumn >

  Page.xaml全部代码如下:

ContractedBlock.gif ExpandedBlockStart.gif Code
<UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  x:Class="SLApplicationDataTest.Page"
    xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:myscreen
="clr-namespace:SLApplicationDataTest"
    xmlns:myconvert
="clr-namespace:SLApplicationDataTest"
    xmlns:mytxtbxsrc
="clr-namespace:SLFilterTextBox;assembly=SLFilterTextBox"
    Width
="600" Height="300">

    
<UserControl.Resources>
        
<myconvert:InvalidToBrushConverter x:Key="myBrushConvert"/>   
        
<myconvert:ErrMsgConverter x:Key="myErrMsgConvert"/>
    
</UserControl.Resources>

        
<Canvas x:Name="LayoutRoot" Width="600" Height="300" Background="Wheat">
        
<StackPanel x:Name="stackPeopleCenter" Height="300"  Width="600" Background="White">
        
<StackPanel Orientation="Horizontal">
            
<Button x:Name="addButton" Content="Add" Margin="10"/>
            
<Button x:Name="deleteButton" Content="Delete" Margin="10"/>
        
</StackPanel>
        
<data:DataGrid x:Name="dgPeople" AutoGenerateColumns="False"  BindingValidationError="dgPeople_BindingValidationError">
            
<data:DataGrid.Columns>
                    
<data:DataGridTemplateColumn Header="Name">
                        
<data:DataGridTemplateColumn.CellTemplate >
                            
<DataTemplate>
                               
<Border Background="{Binding Validator.InvalidName, Converter={StaticResource myBrushConvert }}"
                                       ToolTipService.ToolTip
="{Binding Validator, Converter={StaticResource myErrMsgConvert},,ConverterParameter=Name}">                                   
                                   
<TextBlock  Text="{Binding Name}" ></TextBlock>
                                
</Border>
                            
</DataTemplate>
                        
</data:DataGridTemplateColumn.CellTemplate>
                        
<data:DataGridTemplateColumn.CellEditingTemplate>
                            
<DataTemplate>
                                
<TextBox Text="{Binding Name , Mode=TwoWay, NotifyOnValidationError=True,  ValidatesOnExceptions=True}"
                                         Background
="{Binding Validator.InvalidName, Converter={StaticResource myBrushConvert}}"
                                         ToolTipService.ToolTip
="{Binding Path=Validator, Converter={StaticResource myErrMsgConvert}, ConverterParameter=Name}"
                                         Tag
="Name">                                    
                                
</TextBox>
                            
</DataTemplate>
                        
</data:DataGridTemplateColumn.CellEditingTemplate>
                    
</data:DataGridTemplateColumn>
               
                    
<data:DataGridTemplateColumn Header="Sex">
                        
<data:DataGridTemplateColumn.CellTemplate >
                            
<DataTemplate>
                                
<Border Background="{Binding Validator.InvalidSex, Converter={StaticResource myBrushConvert}}"
                                        ToolTipService.ToolTip
="{Binding Path=Validator, Converter={StaticResource myErrMsgConvert}, ConverterParameter=Sex}">
                                    
<TextBlock  Text="{Binding Sex}"></TextBlock>
                                
</Border>
                            
</DataTemplate>
                        
</data:DataGridTemplateColumn.CellTemplate>
                        
<data:DataGridTemplateColumn.CellEditingTemplate>
                            
<DataTemplate>
                                
<TextBox  Text="{Binding Sex , Mode=TwoWay, NotifyOnValidationError=True,  ValidatesOnExceptions=True}"  
                                         Background
="{Binding Validator.InvalidSex, Converter={StaticResource myBrushConvert}}"
                                         ToolTipService.ToolTip
="{Binding Path=Validator, Converter={StaticResource myErrMsgConvert}, ConverterParameter=Sex}"
                                         Tag
="Sex">
                                
</TextBox>
                            
</DataTemplate>
                        
</data:DataGridTemplateColumn.CellEditingTemplate>
                    
</data:DataGridTemplateColumn>
                
                    
<data:DataGridTemplateColumn Header="Age">
                    
<data:DataGridTemplateColumn.CellTemplate >
                        
<DataTemplate>
                                
<Border Background="{Binding Validator.InvalidAge, Converter={StaticResource myBrushConvert}}"
                                        ToolTipService.ToolTip
="{Binding Path=Validator, Converter={StaticResource myErrMsgConvert}, ConverterParameter=Age}">
                                    
<TextBlock  Text="{Binding Age}"></TextBlock>
                                
</Border>
                        
</DataTemplate>
                    
</data:DataGridTemplateColumn.CellTemplate>
                    
<data:DataGridTemplateColumn.CellEditingTemplate>
                        
<DataTemplate>
                                
<mytxtbxsrc:MyFilterTextBox x:Name="myFilterTBAge" Text="{Binding Age , Mode=TwoWay, NotifyOnValidationError=True,  ValidatesOnExceptions=True}"
                                     Background
="{Binding Validator.InvalidAge, Converter={StaticResource myBrushConvert}}"
                                                             Loaded
="myFilterTBAge_Loaded">
                                
</mytxtbxsrc:MyFilterTextBox>
                            
</DataTemplate>
                    
</data:DataGridTemplateColumn.CellEditingTemplate>
                
</data:DataGridTemplateColumn>
                
<data:DataGridTextColumn     Header="Address"  Binding="{Binding Address}"  />
            
</data:DataGrid.Columns>
        
</data:DataGrid>
    
</StackPanel>
        
<myscreen:PleaseWaitValidate x:Name="myWaitingSexValidateScreen" Visibility="Collapsed" Margin="8,2,2,2" Width="300" Height="150">
        
</myscreen:PleaseWaitValidate>
   
</Canvas>
</UserControl>

修改后台代码,Page.xaml.cs如下:
引入空间:

using  SLFilterTextBox;

定义myFilterTBAge_Loaded事件处理程序:

         private   void  myFilterTBAge_Loaded( object  sender, RoutedEventArgs e)
        {
            ((MyFilterTextBox)sender).MyFilter 
=  SLFilterTextBox.TextBoxFilterType.PositiveInteger;  // 设定MyFilterTextBox控件的过滤属性
        }

 Page.xaml.cs全部代码如下:

ContractedBlock.gif ExpandedBlockStart.gif Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser; //因为要使用HtmlPage.Window.Alert(message));
using SLFilterTextBox;


namespace SLApplicationDataTest
ExpandedBlockStart.gifContractedBlock.gif
{
    
public partial class Page : UserControl
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        People mypeople;

        
public Page()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            InitializeComponent();

            
this.addButton.Click += new RoutedEventHandler(addButton_Click);
            
this.deleteButton.Click += new RoutedEventHandler(deleteButton_Click);
            
this.dgPeople.KeyDown += new KeyEventHandler(peopleDataGrid_KeyDown);
            
          


            Loaded 
+= new RoutedEventHandler(Page_Loaded);
        }


        
private void Page_Loaded(object sender, RoutedEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
ContractedSubBlock.gifExpandedSubBlockStart.gif            
取得数据源数据并绑定到DataGrid控件上#region 取得数据源数据并绑定到DataGrid控件上
            mypeople 
= People.GetTestData();
            
this.dgPeople.ItemsSource = mypeople;
            
#endregion
             
        }


ContractedSubBlock.gifExpandedSubBlockStart.gif        
通过按钮添加新记录行#region 通过按钮添加新记录行
        
void addButton_Click(object sender, RoutedEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
           
// mypeople.Add(new Person());
            mypeople = mypeople.AddNewPerson();
        }

        
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif        
通过按钮删除记录#region 通过按钮删除记录
        
void deleteButton_Click(object sender, RoutedEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            DeletePerson();
        }

        
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif        
删除记录子程序#region 删除记录子程序
        
private void DeletePerson()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (null == this.dgPeople.SelectedItem)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return;
            }

            Person person 
= this.dgPeople.SelectedItem as Person;
            
if (null == person)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return;
            }

            mypeople.Remove(person);
        }

        
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif        
处理键盘响应事件#region 处理键盘响应事件
        
void peopleDataGrid_KeyDown(object sender, KeyEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
ContractedSubBlock.gifExpandedSubBlockStart.gif            
如果是Insert键,则做插入新行操作#region 如果是Insert键,则做插入新行操作
            
if (Key.Insert == e.Key)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                mypeople.Add(
new Person());
            }

            
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif            
如果是Delete键,则做删除操作#region 如果是Delete键,则做删除操作
            
if (Key.Delete == e.Key)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                DeletePerson();
            }

            
#endregion

        }

        
#endregion



ContractedSubBlock.gifExpandedSubBlockStart.gif        
校验错误处理程序#region 校验错误处理程序
        
private void TextBox_BindingValidationError(object sender, ValidationErrorEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{

            
if (e.Action == ValidationErrorEventAction.Added)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
//如果校验出错,则抛出错误提示窗口
                ((Control)e.OriginalSource).Background = new SolidColorBrush(Colors.Red);
                ((Control)e.OriginalSource).SetValue(ToolTipService.ToolTipProperty, e.Error.Exception.Message);
                ((Control)e.OriginalSource).Focus();
                
this.Dispatcher.BeginInvoke(() => HtmlPage.Window.Alert(e.Error.Exception.Message));


            }

            
else if (e.Action == ValidationErrorEventAction.Removed)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
//如果校验通过,则做如下处理
                ((Control)e.OriginalSource).Background = new SolidColorBrush(Colors.White);
                ((Control)e.OriginalSource).SetValue(ToolTipService.ToolTipProperty, 
null);
            }


        }

        
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif        
打开与关闭“等待校验窗口”#region  打开与关闭“等待校验窗口”
        
public void StartWait(string message)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
this.myWaitingSexValidateScreen.DataContext = message;
            
this.myWaitingSexValidateScreen.StartWait();
        }


        
public void EndWait(string message)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
this.myWaitingSexValidateScreen.DataContext = message;
            
this.myWaitingSexValidateScreen.StopWait();
        }

        
#endregion


        
private void dgPeople_BindingValidationError(object sender, ValidationErrorEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (e.Action == ValidationErrorEventAction.Added)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                Person person 
= ((Control)e.OriginalSource).DataContext as Person;
                
if (null != person && null != ((Control)e.OriginalSource).Tag)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    person.Validator.RegisterError(((Control)e.OriginalSource).Tag.ToString(), e.Error.Exception.Message);
                }

                
//((Control)e.Source).Background = new SolidColorBrush(Colors.Red);      
                
//((Control)e.Source).SetValue(ToolTipService.ToolTipProperty, e.Error.Exception.Message);    
            }

            
else if (e.Action == ValidationErrorEventAction.Removed)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                Person person 
= ((Control)e.OriginalSource).DataContext as Person;
                
if (null != person && null != ((Control)e.OriginalSource).Tag)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    person.Validator.ClearError(((Control)e.OriginalSource).Tag.ToString());
                }

                
//((Control)e.Source).Background = new SolidColorBrush(Colors.White);    
                
//((Control)e.Source).SetValue(ToolTipService.ToolTipProperty, null);
            }


        }


        
private void myFilterTBAge_Loaded(object sender, RoutedEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            ((MyFilterTextBox)sender).MyFilter 
= SLFilterTextBox.TextBoxFilterType.PositiveInteger; //设定MyFilterTextBox控件的过滤属性
        }


    }

}

生成项目后运行,然后在Age框内输入数字,可以看到它只接受正整数,录入其它的字符均无反应。
SilverLight学习笔记--实际应用(一) 源代码下载


前往:Silverlight学习笔记清单
本文程序在Silverlight2.0和VS2008环境中调试通过。本文参照了部分网络资料,希望能够抛砖引玉,大家共同学习。
(转载本文请注明出处)

转载于:https://www.cnblogs.com/wsdj-ITtech/archive/2009/09/12/1565454.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值