ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [DataGrid] Data Binding시 Row항목 조사해서 각 Cell 색상 변경.
    Window Programming/Silverlight 2011. 8. 3. 21:41
    728x90

    하고자 하는 작업은 아래와 같음.

    ○ Data Grid에서 특정 컬럼의 날짜 기준으로 초과된 날짜 컬럼은 붉은색 글자로 표시.

    자 일단 Data가 Binding된 후 Row별로 값을 확인해야 된다.

    1) DataGrid의  LoadingRow 이벤트 사용.
       그러면 각 Row가 로딩될때마다 호출되어 Row값을 확인할 수 있다.

    사용법은 e.Row.DataContext 의 값을 Binding된 Data형으로 캐스팅해서 읽어오면 땡!

    그렇다면 현재 Row에서 각 셀의 값을 알았다. 비교하는 로직은 별도로 짜고....
    그 셀에 해당하는 Element정보는 어떻게 참고할 것인가가 중요해지게 된다!

    2) 특정 Cell의 Element 정보를 얻기!

    DataGrid에서 각 Cell에 해당하는 자료형은 DataGridCell이다.

    일단 소스부터.....
     

    private FrameworkElement GetParent(FrameworkElement child, Type targetType)

    {

        object parent = child.Parent;

        if (parent != null)

        {

            if (parent.GetType() == targetType)

            {

                return (FrameworkElement)parent;

            }

            else

            {

                return GetParent((FrameworkElement)parent, targetType);

            }

        }

        return null;

    }
    void Customerdatagrid_LoadingRow(object sender, DataGridRowEventArgs e)
    {
                // CustomerDetail is a table at service side
                ServiceReference1.CustomerDetail clist = e.Row.DataContext asServiceReference1.CustomerDetail;
                FrameworkElement el;
                el = this.Customerdatagrid.Columns[1].GetCellContent(e.Row);
                DataGridCell changeCell = GetParent(el, typeof(DataGridCell)) as DataGridCell;
                SolidColorBrush brush = new SolidColorBrush(Colors.Black);
                if (changeCell != null)
                {
                    if (clist.value > 0)
                    {
                        brush = new SolidColorBrush(Colors.Green);
                    }
                    else if (clist.value < 0)
                    {
                        brush = new SolidColorBrush(Colors.Red);
                    }
                    changeCell.Foreground = brush;
                }
               
        }


    1) ServiceReference1.CustomerDetail clist = e.Row.DataContext asServiceReference1.CustomerDetail;
       -> Row 정보를 얻기

    2)
    el = this.Customerdatagrid.Columns[1].GetCellContent(e.Row);
        ->
    Customerdatagrid는 DataGrid의 이름. Row에서 특정 Column에 해당하는 Element를 리턴한다.

    3)  DataGridCell changeCell = GetParent(cell, typeof(DataGridCell)) as DataGridCell;
         -> 이렇게해서 진짜 Cell의 객체를 얻어낼 수 있다

    이제 특정 조건이 만족할때 

    changeCell.Foreground = new SolidColorBrush(Colors.Red);

    이렇게 색을 바꿔주면 된다.

    ※ 위 조건을 만족 못하는 경우는 다시 색을 되돌려야 하니 예외 처리를 따로 해줘야한다.

    ○  참고자료
    http://www.c-sharpcorner.com/UploadFile/0d4efc/8569/
    http://helpcentral.componentone.com/CS/silverlight_161/f/78/p/78245/214487.aspx

    댓글

Designed by black7375.