2011-04-22 5 views
2

내 viewmodel에서 observablecollection에 데이터 바인딩되는 comboxbox가 있습니다. 내 목록에 데이터를 채울 수 있지만 "- 모든 모델 -"과 같은 기본 항목을 추가하고 싶습니다. 아래의 코드는 "- 모든 모델 -"을 기본 항목으로 표시하지만 다른 항목을 선택하면 선택할 수 없습니다.Wpf Comboxbox 선택 가능한 기본 항목

<ContentControl Content="{Binding Items}"> 
    <ContentControl.ContentTemplate> 
     <DataTemplate> 
      <Grid> 
       <ComboBox x:Name="cb" ItemsSource="{Binding}"/> 
       <TextBlock x:Name="tb" Text="--Choose One--" IsHitTestVisible="False" Visibility="Hidden"/> 
      </Grid> 
      <DataTemplate.Triggers> 
       <Trigger SourceName="cb" Property="SelectedItem" Value="{x:Null}"> 
        <Setter TargetName="tb" Property="Visibility" Value="Visible"/> 
       </Trigger> 
      </DataTemplate.Triggers> 
     </DataTemplate> 
    </ContentControl.ContentTemplate> 
</ContentControl> 

나는 compositecollection으로 시도했지만 작동하지 않는 것 같습니다. 이것을 달성 할 수있는 방법이 있습니까?

미리 감사드립니다.

답변

2

뷰 상호 작용 로직을 뷰 모델에 빌드하십시오. 내 제안에 따라 Observable 컬렉션 유형이 소스 목록에 의해 채워진 뷰 모델과 "선택되지 않은"항목에 대한 뷰 모델 하나가 추가됩니다. 그런 다음 sematic 널과의 selectedItem의 ID를 처리 할 수 ​​

public class ItemViewModel 
{ 
    public string Description { get; set; } 
    public int Id { get; set; } 
} 

public class ViewModel : ViewModelBase 
{   
    public ObservableCollection<ItemViewModel> Items { get; set; } // Bound to ContentControl 

    private void Init() 
    { 
     Items = new ObservableCollection<ItemViewModel>(); 
     Items.Add(new ItemViewModel() { Description = "--choice one--" , Id = null }); 
     Items.AddRange(Model.Items.Select(i=> new ItemViewModel() { Description = i.Description , Id = i.Id })); 
    } 
} 

같은

뭔가.

0

컬렉션 일반 유형을 object으로 변경하고 거기에 모든 모델을 추가 할 수 있습니다.

+0

나는 이것이 실행 가능한 옵션이라고 생각하지 않는다 ... –

4

CompositeCollection 사용 방법을 알고 있다면 제대로 작동합니다. 그것에 대해 한 가지 중요한 점은 DataContext을 상속하지 않는다는 것입니다. 이는 다른 방법으로 소스를 참조해야한다는 것을 의미하며, 그 방법이 x:Reference 인 경우 순환 참조를 만들지 않아야합니다. 참조 된 요소의 Resources에있는 콜렉션. 예 :

<Window.Resources> 
    <CompositeCollection x:Key="compCollection"> 
     <ComboBoxItem Content="-- All Models --"/> 
     <CollectionContainer Collection="{Binding MyCollection, Source={x:Reference Window}}"/> 
    </CompositeCollection> 
    ... 
</Window.Resources> 

그러면 이것을 ItemsSource="{StaticResource compCollection}"을 통해 사용할 수 있습니다.

+0

이것은 훨씬 청결한 대답이다. MVVM 관점에서 보면 훨씬 깔끔합니다. – Oliver