有没有其他方法使用c#创建组合框(而不是SelectionChangedEventHandler)

时间:2014-05-16 14:38:26

标签: c# .net silverlight combobox silverlight-5.0

我在c#工作并使用silverlight5。我遇到了一个问题,我必须使用c#(而不是xaml)来创建组合框,因为我是动态的。

我曾使用SelectionChangedEventHandler这样做,但我想用其他方式替换它,但不知道哪条路?

目前我有这个工作代码:

 ComboBox cb = new ComboBox();
 if (param.Type == "ComboBox") // I am reading xml if there is ComboBox in its node then i create combo box using c# and this "param" is an object
 {

     TextBlock txtblk2 = new TextBlock(); //This textBlock is to print the selected value from Combo Box

     cb.SelectionChanged += new SelectionChangedEventHandler(comboBox1_SelectionChanged);
     cb.SelectedIndex = cb.Items.Count - 1;
     txtblk2.Text = cb.SelectedValue.ToString() + " millions";

 }
 void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) 
 {
     MessageBox.Show("comboBox1_SelectionChanged1");
     txtblk2.Text = cb.SelectedValue.ToString() + " millions";
     txtblk2.FontSize = 14;
 }

有人可以写一些相同的方法来实现相同的使用c#only(非Xaml)必须支持silverlight5吗? 会是一个很大的帮助。感谢。

为什么仅限c#?

实际上我会动态地使用xml,其结构我不知道,我将反序列化它,如果遇到{{1的任何节点,我将使用它获取的对象来访问xml节点值然后我将创建我上面创建的组合框(使用选择更改事件)同样我必须实现但不使用xaml和selction更改事件。

2 个答案:

答案 0 :(得分:1)

为什么不使用XAML?您可以将ListBox与绑定到对象集合的项绑定,并将DataTemplate设置为例如:

<ListBox ItemSource="{Binding DynamicItems}">
     <ListBox.ItemTemplate>
        <DataTemplate>
            <ComboBox Text="{Binding Name}"/>
        </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>

在代码背后:

     if (param.Type == "ComboBox")
     {
          DynamicItem item = new DynamicItem(){Name="param.Name"};
          DynamicItems.Add(item);
     }

然后将自动创建ComboBox。我更喜欢这种方式,因为在后面的代码中创建UI元素看起来很糟糕。

我知道这不是你问题的解决方案,你必须根据你的问题进行调整。

答案 1 :(得分:1)

您可以通过编程方式设置绑定... ...但是,我强烈建议你阅读DataTemplates,你不会对你的“仅限c#code”方法感到满意。

if (param.Type == "ComboBox")
{
    ComboBox cb = new ComboBox();
    TextBlock tb = new TextBlock(){FontSize = 14};
    tb.SetBinding(TextBlock.TextProperty,
      new Binding("SelectedValue")
      {
         Source = cb, StringFormat = "{0} millions"
      });
}
相关问题