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

发布于 2024-12-10 10:44:29 字数 6540 浏览 0 评论 0原文

这听起来可能微不足道,但我在 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 )

有什么想法吗?

This may sound trivial but i have a problem with setting selected item in ComboBox ;)

What i want to achive:

I want to have the first element of the list selected after the page loads.

XAML Code:

               <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>

RESULT:
AG_E_UKNOWN_ERROR [Line:49 Position:55]
Line 49:

</ComboBox>

Error Details

    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 )

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

天荒地未老 2024-12-17 10:44:29

正如我在您的评论中读到的那样,您想要使用一个 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。

As I read in your comments you want to use a ComboBox which automatically has a selection when it is loaded. Therefore I would suggest two possibilities: Writing a control deriving from ComboBox or adding a behavior to a default ComboBox.

Deriving from ComboBox:

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

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

Usage:

<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>

Implementing behavior:

A behavior class allows you to add a behavior to a control using xaml. The behavior is coded.

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;
    }
  }
}

Usage:

<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>

Note, that for the usage of behaviors you need the Blend SDK to be installed.

弥繁 2024-12-17 10:44:29

我怀疑您因 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>

I suspect that you're getting an error because of the SelectionChanged event handler within the DataTemplate. I'm guessubg that the DataGrid you're using this template in can't find the event handler. Why do you need this event handler?

I get a similar error message with the following 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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文