silverlight中Combox绑定数据以及动态绑定默认选定项的用法

简介: 在Sliverlight中,经常要用到下拉框Combox,然而Combox的数据绑定却是一件令初学者很头疼的事情。今天就来总结一下下拉框的使用方法: 下面写一个简单的例子吧。先写一个日期的Model,代码如下: public class Date { public...

在Sliverlight中,经常要用到下拉框Combox,然而Combox的数据绑定却是一件令初学者很头疼的事情。今天就来总结一下下拉框的使用方法:

下面写一个简单的例子吧。先写一个日期的Model,代码如下:

   public class Date
   {
      public string DateName { get; set; }
      public string DateValue { get; set; }
      public Date()
      {
      }
      public Date(string name, string value)
      {
         this.DateName = name;
         this.DateValue = value;
      }
   }

这里就用简单的MVVM模式,再写一个DateViewModel,代码如下:

public class DateViewModel
   {
      public List<Date> Months { get; set; }
      public string  currMonth { get; set; }

      public DateViewModel()
      {
         Months = new List<Date>();
         for (int i = 1; i <= 12; i++)
         {
            Months.Add(new Date(i+"month",i.ToString()));
         }
         currMonth = "3";
      }

   }

在类的构造函数中,初始化所有的月份,以便绑定到前台。到这里后台代码写完了,下面开始绑定下拉框,下面是XAML代码:

<UserControl x:Class="SilverlightMVVM.MainPage"
  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:Silverlight.ViewModel"
  mc:Ignorable="d"
  d:DesignHeight="300" d:DesignWidth="400">
<UserControl.Resources>
  <local:DateViewModel x:Key="DateVM" />
</UserControl.Resources>

<Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource DateVM}}">

  <ComboBox ItemsSource="{Binding Months}"
      SelectedValuePath="DateValue"
      DisplayMemberPath="DateName"
      SelectedValue="{Binding currMonth}"
      Height="23"
      Name="comboBox1"
      Width="120" />

</Grid>
</UserControl>

注意代码中标红的地方,xmlns:local="clr-namespace:Silverlight.ViewModel",这里引入命名空间。

然后绑定到Grid的DataContext上面。

DisplayMemberPath   就是下拉框显示的内容

SelectedValuePath    就是下拉框的Value值

SelectedValue          默认选定的项,可根据绑定的值改变

至此,下拉框的绑定就完成了。

 

目录
相关文章