2011-05-12 2 views
4

MVVM 모델을 사용하여 WPF 창의 목록 상자에 표시하려는 ObservableCollection> 속성이 있습니다. 이상적으로 나는 bool에 대한 체크 박스와 문자열에 대한 레이블이있는 목록 상자를 갖고 싶습니다. 사용자가 체크 상자의 값을 변경하면 해당 bool이 변경됩니다. 이 일을하는 가장 좋은 방법은 무엇입니까?MVVM을 사용하여 옵션 목록 작성

답변

2

MVVM 방식을 따르고 싶다면 ObservableCollection의 모든 요소는 ViewModel이어야합니다.

이 viewModels는 string Descriptionbool IsSelected 2- 속성을 노출한다.

그러면 각 데이터 바인딩 된 ViewModel에 대한 확인란과 텍스트 블록을 표시하기 위해 ListBox를 스타일로 제공하면됩니다.

다음 XAML은 이러한 스타일을 구현합니다. 참고 : 사용자 정의 DataContext는 ObservableCollection<YourClass> Items { get; set; } 속성을 포함하는 ViewModel을 보유해야하며 YourClass는 string Description { get; set; }bool IsSelected { get; set; }을 노출합니다. 당신은 분명히 거기에 INotifyPropertyChanged 마법을 던지기를 원할 것입니다.

<Grid> 
    <Grid.Resources> 

     <Style x:Key="CheckBoxListStyle" TargetType="ListBox"> 
      <Style.Resources> 
       <Style TargetType="ListBoxItem"> 
        <Setter Property="Template"> 
         <Setter.Value> 
          <ControlTemplate TargetType="ListBoxItem"> 
           <StackPanel Orientation="Horizontal"> 
            <CheckBox x:Name="itemChoix" Margin="5,5,0,0" IsChecked="{Binding IsSelected, Mode=TwoWay}" IsEnabled="{Binding IsEnabled, Mode=TwoWay}" /> 
            <TextBlock Margin="5,5,0,0" Text="{Binding Description, Mode=TwoWay}" /> 
           </StackPanel> 
          </ControlTemplate> 
         </Setter.Value> 
        </Setter> 
       </Style> 
      </Style.Resources> 
      <Setter Property="ItemsPanel"> 
       <Setter.Value> 
        <ItemsPanelTemplate> 
         <WrapPanel Orientation="Vertical" /> 
        </ItemsPanelTemplate> 
       </Setter.Value> 
      </Setter> 
      <Setter Property="BorderThickness" Value="0" /> 
     </Style> 

    </Grid.Resources> 

    <Grid.ColumnDefinitions> 
     <ColumnDefinition/> 
    </Grid.ColumnDefinitions> 

    <Grid.RowDefinitions> 
     <RowDefinition Height="25"/> 
     <RowDefinition Height="*"/> 
    </Grid.RowDefinitions> 

    <Border Grid.Row="1" Style="{StaticResource BoxBorder}" Grid.Column="1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"> 
     <Grid> 
      <ListBox ItemsSource="{Binding Path=Items}" SelectionMode="Multiple" Style="{StaticResource CheckBoxListStyle}"/> 
     </Grid> 
    </Border> 

</Grid> 
+0

이것은 정말 좋은 것처럼 보입니다. 솔루션을 구현하고 구현하는 데 시간이 좀 걸립니다. – PlTaylor

+0

나는 거기 90 %의 길이다. ObservableCollection 이있는 기본 뷰 모델이 있습니다. 그런 다음 CheckBoxListItem은 공용 bool IsSelected가있는 뷰 모델입니다. { get { return this.isSelected; } 세트 { this.isSelected = value; this.RaisePropertyChanged ("IsSelected"); } } 확인란을 선택하면 IsSelected가 설정되지만 기본보기 모델에있는 메서드를 실행하려면 어떻게해야합니까? – PlTaylor

+0

IsSelected setter에서 메서드를 호출 할 수 없습니까? –

0
  1. 가에 isSelected 부울 속성을 만들기 당신의 ViewModel에 공개 ObservableCollection에 속성을 만듭니다.
  2. 생성자 또는 명령에서 채우기를 채 웁니다.
  3. IsSelected 속성을 설정하는 확인란의 명령을 만듭니다.
  4. 는 XAML 바인딩을 수행
3

정의, 모델 ItemsControl에를 사용해보십시오, 체크 박스의 목록에 결합하지 않는 : 뷰 모델에서

<ItemsControl ItemsSource="{Binding YourModelList}"> 
    <ItemsPanelTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <CheckBox IsChecked="{Binding Path=Selected}"/> 
       <TextBlock Text="{Binding Path=Description}" /> 
      </StackPanel> 
     </ItemsPanelTemplate> 
</ItemsControl> 

:

public ObservbleCollection<YourModel> YourModelList { get; set; } 

그리고 모델 :

public class YourModel 
{ 
    public bool Selected {get;set;} 
    public string Description {get;set;} 
    public int ID {get;set;} 
} 

필요에 따라 INotifyPropertyChanged 구현

+0

앱을 시작할 때 예외가 발생하는 것 같습니다. ''System.Windows.Controls.ItemCollection '형식의 컬렉션에 값을 추가하면 예외가 발생했습니다.' 줄 번호 '128'및 줄 위치 '23'. 어떤 아이디어? – PlTaylor

+0

ItemCollections 컬렉션? 그 말이 맞지 않아 ... – drowned

관련 문제