0

私はこのコードを持っています:

<ComboBox Name="cbxWorkers" HorizontalContentAlignment="Right"
          ItemsSource="{Binding Workers}">
   <ComboBoxItem IsSelected="True" Content="Select" />
      <ComboBox.ItemTemplate>
         <DataTemplate>
            <ComboBoxItem Content="{Binding LastName}" />
         </DataTemplate>
      </ComboBox.ItemTemplate>
</ComboBox>

2 行目以外はすべて正常に動作します。実行時例外が発生します。ItemsSource を使用する前に、Items コレクションを空にする必要があります。

どのように対処すれば、すべてのワーカーと、コンボボックスの最初のアイテムとして「選択」というアイテムも取得できますか?

どうもありがとう :)

4

2 に答える 2

0

2 つのソースを持つことはできません。選択する項目を ItemsSource からコードで指定する必要があります。

<ComboBox Name="cbxWorkers" HorizontalContentAlignment="Right" ItemsSource="{Binding Workers}">
<ComboBox.ItemTemplate>
    <DataTemplate>
        <ComboBoxItem Content="{Binding LastName}" IsSelected="{Binding isSelected}" />
    </DataTemplate>
</ComboBox.ItemTemplate>

これを行うことも、C#/VB で追加の最初の項目を作成して、それが選択されていることを確認することもできます。

于 2013-08-17T17:12:20.950 に答える
0

でこれを行うことができますCompositeCollection

<ComboBox x:Name="cbxWorkers" SelectedIndex="0">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=LastName}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem Content="Select" />
            <CollectionContainer Collection="{Binding Workers}" />
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

注: をに設定SelectedIndex="0"する必要ComboBoxComboBoxItemあります。ItemsSourceIsSelectedComboBox

編集についてCollectionContainer

@HB が指摘したように、BindingonCollectionContainerはこのようには機能しません。いくつかのオプションがあります。これらはこのCodeProject の記事で説明されているので、ここでは繰り返しません。言及されていない 1 つの方法は、新しい (.NET 4 以降)x:Referenceオプションです。次のように使用されます。

<CollectionContainer Collection="{Binding DataContext.Workers, Source={x:Reference cbxWorkers}}" />
于 2013-08-17T17:21:59.207 に答える