微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐