当前位置: 代码迷 >> Silverlight >> Silverlight的空间Combobox的初始使用)
  详细解决方案

Silverlight的空间Combobox的初始使用)

热度:4336   发布时间:2013-02-26 00:00:00.0
Silverlight的空间Combobox的初步使用)

开始很简单的学了xmal代码如下:但是报错,不知道为什么?

<ComboBox HorizontalAlignment="Left"  VerticalAlignment="Bottom" x:Name="abc" SelectionChanged="abc_SelectionChanged">            <ComboBoxItem Content="1" IsSelected="True" />            <ComboBoxItem Content="2" />            <ComboBoxItem Content="3"  />        </ComboBox>
在代码中获取值是报错的:
ComboBoxItem item = abc.SelectedItem as ComboBoxItem;            txt.Text = item.Content.ToString();

修改代码:不需要 IsSelected="True"也不需要 ItemsSource="{Binding}"才可以运行,但是我又想启动选择第二项。。。怎么办

然后再cs代码中通过abc.SelectedIndex = 2;才有用,哎......

下面看看整个代码吧,很乱,一个是xmal初始内容数据,一个是绑定列表对象:

xmal如下:

<Grid x:Name="LayoutRoot" Background="White" Height="228" Width="378">        <ComboBox x:Name="cbbTest" Height="30" Width="100" ItemsSource="{Binding}" DisplayMemberPath="Id" SelectionChanged="select"/>        <TextBlock Height="30" Width="100" HorizontalAlignment="Center" VerticalAlignment="Bottom" x:Name="txt"></TextBlock>        <ComboBox HorizontalAlignment="Left"   VerticalAlignment="Bottom" x:Name="abc" SelectionChanged="abc_SelectionChanged">            <ComboBoxItem Content="1"  />            <ComboBoxItem Content="2" />            <ComboBoxItem Content="3"  />        </ComboBox>    </Grid>

cs.如下:

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;namespace Combombox{    public partial class MainPage : UserControl    {        public MainPage()        {            InitializeComponent();            getData();            abc.SelectedIndex = 2;        }        List<Class1> lstSource = new List<Class1>();        private void getData() {            lstSource.Add(new Class1 { Id="1",Name="oracle"});            lstSource.Add(new Class1 { Id = "2", Name = "java" });            lstSource.Add(new Class1 { Id = "3", Name = "linux" });            lstSource.Add(new Class1 { Id = "4", Name = "windows 8" });            cbbTest.ItemsSource = lstSource;            cbbTest.SelectedIndex = 0;        }        private void select(object sender, SelectionChangedEventArgs e)        {            string selectedId = (cbbTest.SelectedItem as Class1).Name;            txt.Text = selectedId;        }        private void abc_SelectionChanged(object sender, SelectionChangedEventArgs e)        {            ComboBoxItem item = abc.SelectedItem as ComboBoxItem;            txt.Text = item.Content.ToString();        }    }}

数据类如下:

namespace Combombox{    public class Class1    {        public string Name { get ;set;}        public string Id { get; set; }    }}
最后给出效果吧:


  相关解决方案