【问题标题】:How to set SelectedIndex property for ComboBox in DataTemplate如何在 DataTemplate 中为 ComboBox 设置 SelectedIndex 属性
【发布时间】:2011-10-17 08:29:28
【问题描述】:

这听起来可能微不足道,但我在 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,字符串名称) w MS.Internal.XcpImports.DataTemplate_LoadContent(DataTemplate 模板) w System.Windows.Controls.DataGridTemplateColumn.GenerateElement(DataGridCell 单元格,对象数据项) w System.Windows.Controls.DataGrid.PopulateCellContent(布尔 isCellEdited,DataGridColumn dataGridColumn,DataGridRow dataGridRow,DataGridCell dataGridCell) w System.Windows.Controls.DataGrid.AddNewCellPrivate(DataGridRow 行,DataGridColumn 列) 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(对象发送者,NotifyCollectionChangedEventArgs e) w System.Windows.Data.PagedCollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs 参数) w System.Windows.Data.PagedCollectionView.ProcessAddEvent(对象添加项,Int32 addIndex) w System.Windows.Data.PagedCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs 参数) w System.Windows.Data.PagedCollectionView.<.ctor>b__0(对象发送者,NotifyCollectionChangedEventArgs 参数) 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.b__11(LoadOperation lo) w System.ServiceModel.DomainServices.Client.LoadOperation.c__DisplayClass4`1.b__0(LoadOperation`1 arg) w System.ServiceModel.DomainServices.Client.LoadOperation`1.InvokeCompleteAction() w System.ServiceModel.DomainServices.Client.OperationBase.Complete(对象结果) w System.ServiceModel.DomainServices.Client.LoadOperation.Complete(DomainClientResult 结果) w System.ServiceModel.DomainServices.Client.DomainContext.CompleteLoad(IAsyncResult asyncResult) w System.ServiceModel.DomainServices.Client.DomainContext.c__DisplayClass1b.b__17(Object ) 引起:AG_E_UNKNOWN_ERROR [行:49 位置:55] w MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cvData) w MS.Internal.XcpImports.MethodEx(DependencyObject obj,字符串名称) w MS.Internal.XcpImports.DataTemplate_LoadContent(DataTemplate 模板) w System.Windows.Controls.DataGridTemplateColumn.GenerateElement(DataGridCell 单元格,对象数据项) w System.Windows.Controls.DataGrid.PopulateCellContent(布尔 isCellEdited,DataGridColumn dataGridColumn,DataGridRow dataGridRow,DataGridCell dataGridCell) w System.Windows.Controls.DataGrid.AddNewCellPrivate(DataGridRow 行,DataGridColumn 列) 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(对象发送者,NotifyCollectionChangedEventArgs e) w System.Windows.Data.PagedCollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs 参数) w System.Windows.Data.PagedCollectionView.ProcessAddEvent(对象添加项,Int32 addIndex) w System.Windows.Data.PagedCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs 参数) w System.Windows.Data.PagedCollectionView.<.ctor>b__0(对象发送者,NotifyCollectionChangedEventArgs 参数) 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.b__11(LoadOperation lo) w System.ServiceModel.DomainServices.Client.LoadOperation.c__DisplayClass4`1.b__0(LoadOperation`1 arg) w System.ServiceModel.DomainServices.Client.LoadOperation`1.InvokeCompleteAction() w System.ServiceModel.DomainServices.Client.OperationBase.Complete(对象结果) w System.ServiceModel.DomainServices.Client.LoadOperation.Complete(DomainClientResult 结果) w System.ServiceModel.DomainServices.Client.DomainContext.CompleteLoad(IAsyncResult asyncResult) w System.ServiceModel.DomainServices.Client.DomainContext.c__DisplayClass1b.b__17(Object)

有什么想法吗?

【问题讨论】:

  • 问题会不会是在添加项目之前设置了选定的索引?您可以尝试在加载窗口或控件后设置索引。除此之外:SelectionChanged 方法中做了什么?
  • 选择更改会简单地重定向到另一个网页。没什么花哨的,没有 SelectedIndex 属性可以正常工作。嗯,我如何从 Page 的代码后面访问 DataTemplate 对象属性?好像这样。DeviceComboBox 不起作用。
  • 如果你想创建一个具有特殊行为的 ComboBox,我建议创建一个派生自 ComboBox 并实现你的行为的新类。那应该可以完成工作,并且您不需要数据模板。另一种方法是创建一个 Behavior 元素。

标签: c# silverlight xaml


【解决方案1】:

正如我在您的 cmets 中所读到的,您想使用一个 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。

【讨论】:

    【解决方案2】:

    我怀疑您收到错误是因为DataTemplate 中的SelectionChanged 事件处理程序。我猜你使用这个模板的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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 2016-06-07
      • 2010-11-18
      • 1970-01-01
      • 2011-03-08
      相关资源
      最近更新 更多