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; }
    }
}
最後給出效果吧:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章