silverlight:Silverlight AutoCompleteBox(自动完成输入框Control控件)使用思路方法

  本文举例源代码或素材下载

  在微软Silverlight 开源Control控件项目“Silverlight Toolkit”中提供了个自动完成输入框Control控件:AutoCompleteBox 

  该Control控件功能就是完成类似于google,或baidu中搜索输入框提示(选项)等功能如下图所示:

Silverlight AutoCompleteBox(自动完成输入框Control控件)使用思路方法

  下面是AutoCompleteBox运行效果图:

Silverlight AutoCompleteBox(自动完成输入框Control控件)使用思路方法

  好下面就简要介绍下这个Control控件使用思路方法:

  首先我们要新创建个SilverlightApplication项目然后要准备个数据源也就是当我们输入内容时弹出下拉列

  表框(这里就暂且这么说吧)中显示相似提示信息这里为了方便起见我直接用其源码举例中硬编码类来表示数据源

  然后面还会介绍如何使用WCF来加载数据源信息这里先创建个Employee(雇员信息)类如下:

public sealed partial Employee
{
  public FirstName { get; ; }
  public LastName { get; ; }
  public DisplayName
  {
    get
    {
       FirstName + " " + LastName;
    }
  }
  public Employee
  {
  }
  ernal Employee( firstName, lastName)
  {
    FirstName = firstName;
    LastName = lastName;
  }
  public override
  {
     DisplayName;
  }
  Sample data#region Sample data
  public IEnumerable<Employee> AllExecutives
  {
    get
    {
      yield Employee("Walid", "Abu-Hadba");
      yield Employee("J", "Allard");
      yield Employee("Klaus", "Holse Andersen");
      yield Employee("Nancy", "Anderson");
      yield Employee("Brian", "Arbogast");
      yield Employee("Orlando", "Ayala");
      yield Employee("Robert J.", "Bach");
      yield Employee("Martha", "Béjar");
      yield Employee("Joe", "Belfiore");
      yield Employee("Sue", "Bevington");
      yield Employee("Frank H.", "Brod");
      yield Employee("Brad", "Brooks");
      yield Employee("Lisa", "Brummel");
      yield Employee("Tom", "Burt");
      yield Employee("Chris", "Capossela");
      yield Employee("Scott", "Charney");
      yield Employee("Debra", "Chrapaty");
      yield Employee("Jean-Philippe", "Courtois");
      yield Employee("Alain", "Crozier");
      yield Employee("Kurt", "DelBene");
      yield Employee("Michael", "Delman");
      yield Employee("Joe", "DeVaan");
      yield Employee("Gerri", "Elliott");
      yield Employee("Stephen", "Elop");
      yield Employee("Ben", "Fathi");
      yield Employee("Grant", "George");
      yield Employee("Tom", "Gibbons");
      yield Employee("L. Michael", "Golden");
      yield Employee("Alexander", "Gounares");
      yield Employee("Steve", "Guggenheimer");
      yield Employee("Anoop", "Gupta");
      yield Employee("Tony", "Hey");
      yield Employee("Yasuyuki", "Higuchi");
      yield Employee("Roz", "Ho");
      yield Employee("Kathleen", "Hogan");
      yield Employee("Frank", "Holland");
      yield Employee("Todd", "Holmdahl");
      yield Employee("Darren", "Huston");
      yield Employee("Rajesh", "Jha");
      yield Employee("Chris", "Jones");
      yield Employee("Erik", "Jorgensen");
      yield Employee("Rich", "Kaplan");
      yield Employee("Bob", "Kelly");
      yield Employee("Jawad", "Khaki");
      yield Employee("Shane", "Kim");
      yield Employee("Peter", "Klein");
      yield Employee("Mitchell L.", "Koch");
      yield Employee("Ted", "Kummert");
      yield Employee("Julie", "Larson-Green");
      yield Employee("Antoine", "Leblond");
      yield Employee("Andrew", "Lees");
      yield Employee("John M.", "Lervik");
      yield Employee("Lewis", "Levin");
      yield Employee("Dan'l", "Lewin");
      yield Employee("Moshe", "Lichtman");
      yield Employee("Christopher", "Liddell");
      yield Employee("Steve", "Lfick");
      yield Employee("Brian", "MacDonald");
      yield Employee("Ron", "Markezich");
      yield Employee("Maria", "Martinez");
      yield Employee("Mich", "Mathews");
      yield Employee("Don A.", "Mattrick");
      yield Employee("Joe", "Matz");
      yield Employee("Brian", "McAndrews");
      yield Employee("Richard", "McAnf");
      yield Employee("Yusuf", "Mehdi");
      yield Employee("Jim", "Minervino");
      yield Employee("William H.", "Mitchell");
      yield Employee("Jens Wher", "Moberg");
      yield Employee("Mindy", "Mount");
      yield Employee("Bob", "Muglia");
      yield Employee("Craig", "Mundie");
      yield Employee("Terry", "Myerson");
      yield Employee("Satya", "Nadella");
      yield Employee("Mike", "Nash");
      yield Employee("Peter", "Neupert");
      yield Employee("Ray", "Ozzie");
      yield Employee("Gurdeep", "Singh Pall");
      yield Employee("Michael", "Park");
      yield Employee("Umberto", "Paolucci");
      yield Employee("Sanjay", "Parthasarathy");
      yield Employee("Pamela", "Passman");
      yield Employee("Alain", "Peracca");
      yield Employee("Todd", "Peters");
      yield Employee("Joe", "Peterson");
      yield Employee("Marshall C.", "Phelps, Jr.");
      yield Employee("Scott", "Pitasky");
      yield Employee("Will", "Poole");
      yield Employee("Rick", "Rashid");
      yield Employee("Tami", "Reller");
      yield Employee("J.", "Ritchie");
      yield Employee("Enrique", "Rodriguez");
      yield Employee("Eduardo", "Rosini");
      yield Employee("Jon", "Roskill");
      yield Employee("Eric", "Rudder");
      yield Employee("John", "Schappert");
      yield Employee("Tony", "Scott");
      yield Employee("Jeanne", "Sheldon");
      yield Employee("Harry", "Shum");
      yield Employee("Steven", "Sinofsky");
      yield Employee("Brad", "Smith");
      yield Employee("Mary E.", "Snapp");
      yield Employee("Amitabh", "Srivastava");
      yield Employee("Kirill", "Tatarinov");
      yield Employee("Jeff", "Teper");
      yield Employee("David", "Thompson");
      yield Employee("Rick", "Thompson");
      yield Employee("Brian", "Tobey");
      yield Employee("David", "Treadwell");
      yield Employee("B. Kevin", "Turner");
      yield Employee("David", "Vaskevitch");
      yield Employee("Bill", "Veghte");
      yield Employee("Henry P.", "Vigil");
      yield Employee("Robert", "Wahbe");
      yield Employee("Todd", "Warren");
      yield Employee("Allison", "Watson");
      yield Employee("Blair", "Westlake");
      yield Employee("Simon", "Witts");
      yield Employee("Robert", "Youngjohns");
      yield Employee("Ya-Qin", "Zhang");
      yield Employee("George", "Zinn");
    }
  }
  #endregion
}
public SampleEmployeeCollection : ObjectCollection
{
  public SampleEmployeeCollection : base(Employee.AllExecutives)
  {}
}


  我们从代码中看到Employee类静态属性“AllExecutives”最终被绑定在SampleEmployeeCollection构造思路方法中

  接着为了能够在XAML文件中使用AutoCompleteBoxControl控件还需要添加相应DLL引用(请从下载源码包中获取相应DLL文

  件并引用到项目中来)如下图所示:

Silverlight AutoCompleteBox(自动完成输入框Control控件)使用思路方法

  完成了这步的后就是将相应NameSpace添加到XAML头部以便于在XAML文件中进行Control控件定义如下:

xmlns:controls="clr-:Microsoft.Windows.Controls;assembly=Microsoft.Windows.Controls"

  接下来就是引用相应数据源信息了如下(SampleEmployeeCollection就是上面CS代码中雇员信息类):  

<UserControl.Resources>
    <samples:SampleEmployeeCollectionx:Key="SampleEmployees"/>
</UserControl.Resources>


  这时该轮到AutoCompleteBox“闪亮登场”了:

<controls:AutoCompleteBoxx:Name="autoComplete1"IsTextCompletionEnabled="True"Width="200"Height="25"Grid.Row="0"
   Grid.Column="1"Margin="0+0,8+8"HorizontalAlignment="Left" ItemsSource="{StaticResourceSampleEmployees}"/>


  我们运行看看效果如何样:

Silverlight AutoCompleteBox(自动完成输入框Control控件)使用思路方法

  代码很简单不是吗?下面接着介绍下上面有关该Control控件两个属性:

  IsTextCompletionEnabled:该属性为True时用于将当前被查询到条记录信息暂时放在Control控件输入框中

  (text属性)上图中已看到

  ItemsSource:用于绑定相应数据源信息({StaticResourceSampleEmployees})

  当然如果将该属性设置为False时则该Control控件在显示下拉列表时将不在输入框中设置第条记录信息这里为了提

  高下难度我们将会自定义下“提示框”样式代码如下(注意其中AutoCompleteBox.ItemTemplate部分代码):

<controls:AutoCompleteBoxx:Name="autoComplete2"IsTextCompletionEnabled="False"Width="200"Height="25"Grid.Row="1"
 Grid.Column="1"Margin="0+0,8+8"HorizontalAlignment="Left" ItemsSource="{StaticResourceSampleEmployees}">
 <controls:AutoCompleteBox.ItemTemplate>
  <DataTemplate>
    <GridWidth="200">
      <Grid.ColumnDefinitions>
        <ColumnDefinitionWidth="100"/>
        <ColumnDefinitionWidth="100"/>
      </Grid.ColumnDefinitions>
      <TextBlock HorizontalAlignment="Left" Foreground="Gray" Text="{BindingFirstName}" Grid.Column="0" />
      <TextBlock HorizontalAlignment="Left" Foreground="Gray" Text="{BindingLastName}" Grid.Column="1" />
    </Grid>
  </DataTemplate>
 </controls:AutoCompleteBox.ItemTemplate>
</controls:AutoCompleteBox>


  该Control控件运行效果如下图所示:

Silverlight AutoCompleteBox(自动完成输入框Control控件)使用思路方法

  当然该Control控件模版方式还支持外部声明定义并在Control控件内部进行引用(通过属性ItemTemplate绑定)下面首先

  是样式模版定义: 

<StackPanel.Resources>
  <DataTemplatex:Key="EmployeeDataTemplate">
    <GridWidth="200">
      <Grid.Background>
        <SolidColorBrushColor="Blue"/>
      </Grid.Background>
      <TextBlockForeground="#22ffffff" Margin="0+0,8+8"FontSize="14"Text="{BindingDisplayName}"/>
      <StackPanelHorizontalAlignment="Right"Margin="0+0,8+8">
        <TextBlockHorizontalAlignment="Right"Foreground="White"
         Text="{BindingFirstName}"Padding="2"/>
        <TextBlockHorizontalAlignment="Right"Foreground="White"
         FontSize="12"Text="{BindingLastName}"Padding="2"/>
      </StackPanel>
    </Grid>
  </DataTemplate>
</StackPanel.Resources>


  下面是将上述模版绑定到当前AutoCompleteBox挖件声明代码(注意相应ItemTemplate属性):

  <controls:AutoCompleteBoxx:Name="ArrivalAirport"
            MinimumPrefixLength="1" SearchMode="StartsWithCaseSensitive"
            IsTextCompletionEnabled="False"
            Width="228"Height="25"
            HorizontalAlignment="Left"Margin="0+0,8+8"
            ItemsSource="{StaticResourceSampleEmployees}"
            ItemTemplate="{StaticResourceEmployeeDataTemplate}"/>


  其运行效果如下图所示:

Silverlight AutoCompleteBox(自动完成输入框Control控件)使用思路方法

  当然上面Control控件声明代码中又引入了两个重要属性即:

  SearchMode:查询方式其提供了对当前已输入查询方式有如下几种枚举值:

     StartsWithCaseSensitive:以大写已输入方式开始
     StartsWith:以已输入开始(不区别大小写)
     Contains:是否包含已输入
     ContainsCaseSensitive:是否包含已输入大写.
     Equals:是否相等
     EqualsCaseSensitive:是否大写相等
     .


  MinimumPrefixLength:用于当输入串达到该属性值时才显示下拉列表框

  上面所演示 3种情况基本上就可以满足我们日常开发需要了当然该Control控件还提供了不少事件思路方法

  属性来提供更高级使用方式:

  1.对已输入数据信息进行下拉列表数据自定义事件比如该Control控件提供了Populating来进行相应处理

  如我们在XAML中定义如下代码:

<controls:AutoCompleteBoxx:Name="NowAutoComplete"SearchMode="None"Width="200"Height="25"Grid.Column="1"
   IsTextCompletionEnabled="True"Grid.Row="3"HorizontalAlignment="Left"Margin="0+0,0+12"/>


  然后在后台CS代码中进行下面事件绑定: 

  NowAutoComplete.PopulatingOnPopulatingSynchronous;

  其相应事件处理代码如下:

  privatevoidOnPopulatingSynchronous(objectsender,PopulatingEventArgse)
    {
      AutoCompleteBoxsource=(AutoCompleteBox)sender;
      source.ItemsSource=
      {
        e.Parameter+"后续内容1",
        e.Parameter+"后续内容2",
        e.Parameter+"后续内容3",
      };     
    }


  这时我们运行下看看效果:

Silverlight AutoCompleteBox(自动完成输入框Control控件)使用思路方法

  2.在其它Control控件(Datagrid)中嵌入该Control控件代码如下(注意controls:AutoCompleteBox部分):

<data:DataGridx:Name="MyDataGrid"AutoGenerateColumns="False"Grid.Column="1"Width="290"Grid.Row="5"
  Margin="0+0,0+8"ItemsSource="{StaticResourceSampleEmployees}">
  <data:DataGrid.Columns>
    <data:DataGridTemplateColumnHeader="DisplayName">
      <data:DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
          <controls:AutoCompleteBoxHorizontalAlignment="Left"Width="180"IsTabStop="True"
              ItemsSource="{StaticResourceSampleEmployees}"
              Text="{BindingDisplayName,Mode=TwoWay}"/>
        </DataTemplate>
      </data:DataGridTemplateColumn.CellEditingTemplate>
    </data:DataGridTemplateColumn>
    <data:DataGridTextColumnBinding="{BindingFirstName}"Header="FirstName"/>
  </data:DataGrid.Columns>
</data:DataGrid>


  其运行如下图所示:

Silverlight AutoCompleteBox(自动完成输入框Control控件)使用思路方法

  最后我们将话题深入看看如何使用wcf来获取相应下拉列表数据项当然这里还是用到了的前

  讲过事件“Populating”不过的前我们还要先创建个silverlight wcf,如下:

Silverlight AutoCompleteBox(自动完成输入框Control控件)使用思路方法

  当然我们在WCF端还是用到了的前创建Employee类文件(当然为了避免冲突改名为:EmployeeInfo)

  另外在服务思路方法上使用下面代码来实现数据访问:

[ServiceContract(Namespace="")]
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
publicAutoCompletedService
{
  [OperationContract]
  publicList<EmployeeInfo>GetEmployeeCollection(name)
  {
    List<EmployeeInfo>EmpolyeeList=List<EmployeeInfo>;
    foreach(EmployeeInfoeiin(fromemployeeinfoinEmployeeInfo.AllExecutives
                   whereemployeeinfo.DisplayName.StartsWith(name)
                   selectemployeeinfo))
    {
      EmpolyeeList.Add(ei);
    }
    EmpolyeeList;
  }
} 


  通过添加WEB服务引用方式系统会为我们创建相应代码类文件这里就不多说了下面是Silverlight

  端代码:

voidPage_Loaded(objectsender,RoutedEventArgse)
{
  WCFAutoComplete.IsTextCompletionEnabled=false;
  WCFAutoComplete.SearchMode=AutoCompleteSearchMode.None;
  WCFAutoComplete.Populating(s,args)=>
  {
    args.Cancel=true;
    AutoCompletedServiceClientacsc=AutoCompletedServiceClient;
    acsc.GetEmployeeCollectionCompletedEventHandler<GetEmployeeCollectionCompletedEventArgs>
                          (acsc_GetEmployeeCollectionCompleted);
    acsc.GetEmployeeCollectionAsync(args.Parameter,s);
  };
}




  相应返回数据事件处理代码如下:

voidacsc_GetEmployeeCollectionCompleted(objectsender,GetEmployeeCollectionCompletedEventArgse)
{
  AutoCompleteBoxacb=e.UserStateasAutoCompleteBox;
  (acb!=null&&e.Errornull&&!e.Cancelled)
  {   
    (e.Result.Count>0)
    {
      List<>employeeStrList=List<>;
      foreach(EmployeeInfoemployeeinfoine.Result)
      {
        employeeStrList.Add(employeeinfo.FirstName+""+employeeinfo.LastName);
      }
      acb.ItemsSource=employeeStrList;
      acb.PopulateComplete;
    }
  }
}


  运行时效果如下图所示:

Silverlight AutoCompleteBox(自动完成输入框Control控件)使用思路方法

  当然这里会有个问题就是当我对上面代码“acb.ItemsSource = employeeStrList;”换成:

  “acb.ItemsSource = e.Result;”的后会出现在下面列表中显示数据是该类类型type信息

  想这可能是该Control控件个BUG即在异步情况下进行数据(源)绑定时信息类型不正确当然如果您知

  道是什么问题并有解决方案不妨通过我这里表示感谢了



Tags:  silverlight2 silverlight.2.0 silverlight是什么 silverlight

延伸阅读

最新评论

发表评论