如何在DataTemplate中为ComboBox设置SelectedIndex属性

时间:2011-10-17 08:29:29

标签: c# silverlight xaml

这可能听起来微不足道,但我在ComboBox中设置所选项目有问题;)

我想要实现的目标:

我希望在页面加载后选择列表的第一个元素。

XAML代码:

               <DataTemplate>
                                    <ComboBox x:Name="DeviceComboBox" SelectedIndex="1" SelectionChanged="DeviceComboBox_SelectionChanged">
                                        <ComboBox.Items>
                                            <ComboBoxItem x:Name="Switch" Content="Switche"/>
                                            <ComboBoxItem x:Name="Firewall" Content="Firewalle"/>
                                            <ComboBoxItem x:Name="Host" Content="Hosty" />
                                            <ComboBoxItem x:Name="SRF1" Content="SRF1"/>
                                        </ComboBox.Items>
                                    </ComboBox>
                                </DataTemplate>

结果: AG_E_UKNOWN_ERROR [线路:49位置:55] 第49行:

</ComboBox>

错误详情

    w MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cvData)
    w MS.Internal.XcpImports.MethodEx(DependencyObject obj, String name)
    w MS.Internal.XcpImports.DataTemplate_LoadContent(DataTemplate template)
    w System.Windows.Controls.DataGridTemplateColumn.GenerateElement(DataGridCell cell, Object dataItem)
    w System.Windows.Controls.DataGrid.PopulateCellContent(Boolean isCellEdited, DataGridColumn dataGridColumn, DataGridRow dataGridRow, DataGridCell dataGridCell)
    w System.Windows.Controls.DataGrid.AddNewCellPrivate(DataGridRow row, DataGridColumn column)
    w System.Windows.Controls.DataGrid.CompleteCellsCollection(DataGridRow dataGridRow)
    w System.Windows.Controls.DataGrid.GenerateRow(Int32 rowIndex, Int32 slot, Object dataContext)
    w System.Windows.Controls.DataGrid.InsertElementAt(Int32 slot, Int32 rowIndex, Object item, DataGridRowGroupInfo groupInfo, Boolean isCollapsed)
    w System.Windows.Controls.DataGrid.InsertRowAt(Int32 rowIndex)
    w System.Windows.Controls.DataGridDataConnection.NotifyingDataSource_CollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
    w System.Windows.Data.PagedCollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
    w System.Windows.Data.PagedCollectionView.ProcessAddEvent(Object addedItem, Int32 addIndex)
    w System.Windows.Data.PagedCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args) 
    w System.Windows.Data.PagedCollectionView.<.ctor>b__0(Object sender, NotifyCollectionChangedEventArgs args)
    w System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    w System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item)
    w System.Collections.ObjectModel.Collection`1.Add(T item)
    w LANOS.Views.Customers.onCustomerListLoaded(LoadOperation`1 loadOper)
    w System.ServiceModel.DomainServices.Client.DomainContext.<>c__DisplayClass13`1.<Load>b__11(LoadOperation lo)
    w System.ServiceModel.DomainServices.Client.LoadOperation.<>c__DisplayClass4`1.<Create>b__0(LoadOperation`1 arg)
    w System.ServiceModel.DomainServices.Client.LoadOperation`1.InvokeCompleteAction()
    w System.ServiceModel.DomainServices.Client.OperationBase.Complete(Object result)
    w System.ServiceModel.DomainServices.Client.LoadOperation.Complete(DomainClientResult result)
    w System.ServiceModel.DomainServices.Client.DomainContext.CompleteLoad(IAsyncResult asyncResult)
    w System.ServiceModel.DomainServices.Client.DomainContext.<>c__DisplayClass1b.<Load>b__17(Object )

Caused by: AG_E_UNKNOWN_ERROR [Line: 49 Position: 55]

    w MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cvData)
    w MS.Internal.XcpImports.MethodEx(DependencyObject obj, String name)
    w MS.Internal.XcpImports.DataTemplate_LoadContent(DataTemplate template)
    w System.Windows.Controls.DataGridTemplateColumn.GenerateElement(DataGridCell cell, Object dataItem)
    w System.Windows.Controls.DataGrid.PopulateCellContent(Boolean isCellEdited, DataGridColumn dataGridColumn, DataGridRow dataGridRow, DataGridCell dataGridCell)
    w System.Windows.Controls.DataGrid.AddNewCellPrivate(DataGridRow row, DataGridColumn column)
    w System.Windows.Controls.DataGrid.CompleteCellsCollection(DataGridRow dataGridRow)
    w System.Windows.Controls.DataGrid.GenerateRow(Int32 rowIndex, Int32 slot, Object dataContext)
    w System.Windows.Controls.DataGrid.InsertElementAt(Int32 slot, Int32 rowIndex, Object item, DataGridRowGroupInfo groupInfo, Boolean isCollapsed)
    w System.Windows.Controls.DataGrid.InsertRowAt(Int32 rowIndex)
    w System.Windows.Controls.DataGridDataConnection.NotifyingDataSource_CollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
    w System.Windows.Data.PagedCollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
    w System.Windows.Data.PagedCollectionView.ProcessAddEvent(Object addedItem, Int32 addIndex)
    w System.Windows.Data.PagedCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args)
    w System.Windows.Data.PagedCollectionView.<.ctor>b__0(Object sender, NotifyCollectionChangedEventArgs args)
    w System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    w System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item)
    w System.Collections.ObjectModel.Collection`1.Add(T item)
    w LANOS.Views.Customers.onCustomerListLoaded(LoadOperation`1 loadOper)
    w System.ServiceModel.DomainServices.Client.DomainContext.<>c__DisplayClass13`1.<Load>b__11(LoadOperation lo)
    w System.ServiceModel.DomainServices.Client.LoadOperation.<>c__DisplayClass4`1.<Create>b__0(LoadOperation`1 arg)
    w System.ServiceModel.DomainServices.Client.LoadOperation`1.InvokeCompleteAction()
    w System.ServiceModel.DomainServices.Client.OperationBase.Complete(Object result)
    w System.ServiceModel.DomainServices.Client.LoadOperation.Complete(DomainClientResult result)
    w System.ServiceModel.DomainServices.Client.DomainContext.CompleteLoad(IAsyncResult asyncResult)
    w System.ServiceModel.DomainServices.Client.DomainContext.<>c__DisplayClass1b.<Load>b__17(Object )

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

当我在你的评论中读到你想要使用一个ComboBox时,它会在加载时自动选择。因此,我建议两种可能性:编写一个从ComboBox派生的控件或将行为添加到默认的ComboBox。

从ComboBox派生:

public class MyComboBox : ComboBox
{
  public MyComboBox()
  {
    Loaded += ComboBoxLoaded;
  }

  private void ComboBoxLoaded(object sender, RoutedEventArgs e)
  {
    if(Count > 1)
    {
      SelectedIndex = 1;
    }
  }
}

用法:

<MyComboBox>
  <ComboBoxItem x:Name="Switch" Content="Switche"/>
  <ComboBoxItem x:Name="Firewall" Content="Firewalle"/>
  <ComboBoxItem x:Name="Host" Content="Hosty" />
  <ComboBoxItem x:Name="SRF1" Content="SRF1"/>
</MyComboBox>

实施行为:

行为类允许您使用xaml向控件添加行为。行为已编码。

public class ComboBoxSelectionBehavior:Behavior<ComboBox>
{
  protected override void OnAttached()
  {
    base.OnAttached();
    AssociatedObject.Loaded += ComboBoxLoaded;
  }

  protected override void OnDetaching()
  {
    AssociatedObject.Loaded -= ComboBoxLoaded;
    base.OnDetaching();
  }

  private void ComboBoxLoaded(object sender, RoutedEventArgs e)
  {
    if(Count > 1)
    {
      SelectedIndex = 1;
    }
  }
}

用法:

<ComboBox>
  <Interactivity:Interaction.Behaviors>
    <Behaviors:ComboBoxSelectionBehavior/>
  </Interactivity:Interaction.Behaviors>
  <ComboBoxItem x:Name="Switch" Content="Switche"/>
  <ComboBoxItem x:Name="Firewall" Content="Firewalle"/>
  <ComboBoxItem x:Name="Host" Content="Hosty" />
  <ComboBoxItem x:Name="SRF1" Content="SRF1"/>
</ComboBox>

请注意,对于行为的使用,您需要安装Blend SDK。

答案 1 :(得分:0)

由于SelectionChanged中的DataTemplate事件处理程序,我怀疑您收到错误。我猜你正在使用这个模板的DataGrid无法找到事件处理程序。为什么需要这个事件处理程序?

我收到类似的错误消息,其中包含以下XAML:

MainPage.xaml中:

<UserControl x:Class="Example.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <ResourceDictionary Source="Dictionary1.xaml" />
    </UserControl.Resources>
    <ItemsControl ItemsSource="ABC" ItemTemplate="{StaticResource failTemplate}" />
</UserControl>

Dictionary1.xaml:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <DataTemplate x:Name="failTemplate">
        <ComboBox SelectionChanged="ComboBox_SelectionChanged">
            <ComboBoxItem Content="AAA" />
            <ComboBoxItem Content="BBB" />
            <ComboBoxItem Content="CCC" />
        </ComboBox>
    </DataTemplate>
</ResourceDictionary>