将ComboBoxItem添加到Silverlight 4中的ComboBox问题

时间:2010-04-19 22:16:40

标签: c# silverlight combobox silverlight-4.0

我最近将Silverlight应用程序从3升级到4.经过几个小时的攻击,试图解决问题之后,我已将问题缩小到这个范围:

我有一个用户控件,里面有一个ComboBox。 ComboBox有一个ComboBoxItem子项。用户控件公开一个get访问器,它返回ComboBox的Items对象,允许我通过xaml添加额外的ComboBoxItem。

这一切在Silverlight 3中运行良好,但它在Silverlight 4中不起作用。

代码:

//XAML
<UserControl ... >
  <ComboBox Name="myComboBox">
    <ComboBoxItem Content="Select an Item" />
  </ComboBox>
  <!-- All my other stuff -->
</UserControl>

//Code behind
public ItemCollection ListItems
{
   get
   {
     return myComboBox.Items;
   }
}

//Implementation of User-Control
<CustomControl:UserControl ... >
  <CustomControl:UserControl.ListItems>
    <ComboBoxItem Content="Item 1" />
    <ComboBoxItem Content="Item 2" />
    <ComboBoxItem Content="Item 3" />
  </CustomControl:UserControl.ListItems>
</CustomControl:UserControl>

正如我所提到的,这一切在Silverlight 3中都运行良好,但在Silverlight 4中不起作用。

似乎解决方法是删除我的用户控件中的单个ComboBoxItem,但我希望避免,因为我希望它作为默认项。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

为Silverlight 4重写了XAML解析器,使其与WPF更加一致。我非常肯定你期望的行为是SL3中的一个错误,我不认为它会在WPF中以那种方式运行,尽管我从未真正尝试过。

您可以通过enabling quirks mode恢复旧模式,但我不推荐它。相反,我要做的是为组合框创建一个ControlTemplate,以便在没有选择任何内容时显示“选择项目”文本。将它作为组合框中的实际项目实际上只是一个我们一直被迫使用Windows窗体和HTML等技术的黑客,但在Silverlight中似乎将SelectedItem设为null更合适。