代码之家  ›  专栏  ›  技术社区  ›  Donut

Silverlight Datagrid:高亮显示整个列?

  •  0
  • Donut  · 技术社区  · 16 年前

    我有一个 DataGrid 在我的Silverlight应用程序中,并希望在选中列中的任何单元格时“突出显示”整个列。

    [ ] “表示单元格):

    [     ][     ][     ]
    [     ][     ][     ]
    [     ][     ][     ]
    

    [     ][ selected ][     ]
    [     ][          ][     ]
    [     ][          ][     ]
    

    我希望该列中的所有单元格(包括选定的单元格)都“高亮显示”(可以简单地更改背景色):

    [     ][  selected   ][     ]
    [     ][ highlighted ][     ]
    [     ][ highlighted ][     ]
    

    有什么简单的方法吗? 谢谢!

    1 回复  |  直到 16 年前
        1
  •  1
  •   Stephan    16 年前

    这是行为的开始,应该给你指出正确的方向

        public class DataGridHighlightBehavior : Behavior<DataGrid>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
    
            AssociatedObject.CurrentCellChanged += AssociatedObject_CurrentCellChanged;
        }
    
        void AssociatedObject_CurrentCellChanged(object sender, EventArgs e)
        {
            foreach (object i in AssociatedObject.ItemsSource)
            {
                var item = AssociatedObject.CurrentColumn.GetCellContent(i);
                if (item == null)
                    return;
                var parent = GetParent<DataGridCell>(item);
                if (parent != null)
                    parent.Background = new SolidColorBrush(Colors.Red);
            }
        }
    
        public static T GetParent<T>(DependencyObject source)
                where T : DependencyObject
        {
            DependencyObject parent = VisualTreeHelper.GetParent(source);
            while (parent != null && !typeof(T).IsAssignableFrom(parent.GetType()))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
            return (T)parent;
        }
    }