2010-07-01 6 views
2

그리드의 행 수를 제어해야합니다. 가 MVVM 패턴을 사용하지 않고, 내가 코드 숨김 이것을 달성,이 방법 :MVVM에서 가변 그리드 행 수

<UserControl> 
    <Grid x:Name="PART_Host" /> 
</UserControl> 

private void UpdateHost(int rowCount) { 
    PART_Host.RowDefinitions.Clear(); 
    PART_Host.Children.Clear(); 

    for (int i = 1; i <= rowCount; i++) { 
     PART_Host.RowDefinitions.Add(new RowDefinition()); 
     Grid.SetRow(PART_Host.Children[index], i - 1); 
    } 
} 

지금, 나는 MVVM 패턴을 사용하여이 작업을 수행해야합니다. 내 ViewModel에서 필수 rowCount 속성에 액세스 할 수 있지만이 속성이 변경되면보기를 어떻게 업데이트 할 수 있습니까?

감사합니다.

+0

왜 대신 그리드의 StackPanel을 사용할 수 없습니다. stackpanel을 사용하여 구현할 수있는 것처럼 보입니다. 아니면 MVVM을 사용하여 샘플을 시험해보고 싶습니까? – Ragunathan

+0

StackPanel은 세로 크기 조정을 허용하지 않기 때문에. 내 통제 내용이 허용 된 공간을 채우 길 원합니다. –

답변

1

RowDefinition이 속성 인 경우 RowDefinition [] RowDefinitions 속성을 만들고 RowCount 길이의 행 정의 배열을 반환하고 해당 배열을 RowDefinition 속성에 바인딩 할 수 있습니다. 그렇지 않으면 ItemsControl을 사용하여 사용자 정의 컨트롤을 만들어야합니다 원하는 것을 보여주세요 ...

+0

내 자신의 ItemsControl을 만들어야 할 것 같습니다. 고마워;) –

4

첨부 된 속성을 사용해 보셨습니까? 나는 확실하지 오전하지만 당신은 같은 것을 할 수 있습니다

public class GridExtensions 
    { 
     public static Int32 GetGridRowCount(DependencyObject obj) 
     { 
      return (Int32)obj.GetValue(GridRowCountProperty); 
     } 

     public static void SetGridRowCount(DependencyObject obj, UIElementCollection value) 
     { 
      obj.SetValue(GridRowCountProperty, value); 
     } 

     // Using a DependencyProperty as the backing store for GridRowCount. This enables animation, styling, binding, etc... 
     public static readonly DependencyProperty GridRowCountProperty = 
      DependencyProperty.RegisterAttached("GridRowCount", typeof(Int32), typeof(Grid), new FrameworkPropertyMetadata(OnGridRowCountChanged)); 

     public static void OnGridRowCountChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) 
     { 
      if (e.NewValue != null && obj is Grid) 
      { 
       Int32 rowCount = (Int32)e.NewValue; 
       Grid grid = (Grid)obj; 

       grid.RowDefinitions.Clear(); 
       grid.Children.Clear(); 

       for (int i = 1; i <= rowCount; i++) 
       { 
        grid.RowDefinitions.Add(new RowDefinition()); 
        Grid.SetRow(grid.Children[index], i - 1); 
       } 
      } 
     } 
    } 

를 그리고이 좋아 사용

<Grid local:GridExtensions.GridRowCount="10"></Grid> 
+0

그 일을하는 좋은 방법! –

+0

정말 멋진 솔루션입니다! 하지만 각 행에 컨트롤을 삽입해야하며 오버 헤드가 너무 많습니다. 고맙습니다 ! –

+0

'index' 변수가 정의되어 있지 않습니다. 또한 첨부 된 속성이 왜 'Grid.Children' 컬렉션을 지우고 있는지 이해하지 못합니다. 그 외에는 매우 흥미로운 해결책입니다. –

관련 문제