private static void Control_ScrollChanged(object sender, ScrollChangedEventArgs e) { var scrollViewer = sender as ScrollViewer; // 设置自动滚动的最低的差异值 double diffValue = _DiffValue_Default_Value_; try { // 对应 ListBox / ListView / DataGrid 等 Selector var matchParent = WPFControlsUtils.FindParentOfType <System.Windows.Controls.Primitives.Selector>(scrollViewer); if (matchParent != null) { diffValue = GetDiffValue(matchParent); goto CalcLogic; } // 对应方法2 (ItemsControl) var matchItemsControl = WPFControlsUtils.FindParentOfType <System.Windows.Controls.ItemsControl>(scrollViewer); if (matchItemsControl != null) { diffValue = GetDiffValue(matchItemsControl); goto CalcLogic; } // 对应方法1 (ItemsControl) diffValue = GetDiffValue(scrollViewer); goto CalcLogic; } catch (Exception) { diffValue = _DiffValue_Default_Value_; goto CalcLogic; } CalcLogic: // 如果接近底部, 执行滚动逻辑 if (scrollViewer.ScrollableHeight - scrollViewer.VerticalOffset < diffValue) { scrollViewer.ScrollToEnd(); } #if DEBUG string msg = $"实际:{scrollViewer.ScrollableHeight - scrollViewer.VerticalOffset}, 设置:{diffValue}"; System.Diagnostics.Debug.WriteLine(msg); #endif }
static void UpdateColumnStyles(System.Windows.Controls.DataGrid dataGrid) { var parent = WPFControlsUtils.FindParentOfType <UserControl>(dataGrid); var originStyle = GetColumnStyle(parent); // foreach (var column in dataGrid.Columns.OfType<System.Windows.Controls.DataGridTextColumn>()) // TODO 优化参数 DataGridTextColumn foreach (var column in dataGrid.Columns.OfType <System.Windows.Controls.DataGridBoundColumn>()) // 待测试 DataGridBoundColumn { var newStyle = new Style(); newStyle.BasedOn = column.ElementStyle; newStyle.TargetType = originStyle.TargetType; foreach (var setter in originStyle.Setters.OfType <Setter>()) { newStyle.Setters.Add(setter); } column.ElementStyle = newStyle; } }
void Test1(object obj) { Button o = obj as Button; var r = WPFControlsUtils.FindParentOfType <Grid>(o); }
static void Handle_ItemsSource_Changed_ForItemsControl(object sender, EventArgs e) { var ss = WPFControlsUtils.FindParentOfType <System.Windows.Controls.ScrollContentPresenter>(sender as ItemsControl); ss.ScrollOwner.ScrollToEnd(); }
void Test2(object obj) { Button o = obj as Button; // 指定找上上级的 Grid var r = WPFControlsUtils.FindParentOfType <Grid>(o, parentName: "g0"); }