当前位置: 首页 > 编程语言 > C#

从C#访问ListBox的ScrollViewer分享

时间:2023-04-10 21:30:58 C#

C#学习教程:C#访问ListBox的ScrollViewer我在Stackoverflow上发现了这个问题。我采纳了接受的答案的建议,并将ScrollViewer作为子类的属性公开。但是,这似乎不适用于下面显示的示例。该问题中的一些评论还表明该技术不起作用。XAML:C#:usingSystem;使用System.Windows;使用System.Windows.Controls;命名空间StackoverflowListBoxScrollViewer{publicclassMyListBox:ListBox{publicSc??rollViewerScrollViewer{get{return(ScrollViewer)GetTemplateChild("ScrollViewer");}}}publicpartialclassMainWindow:Window{publicMainWindow(){InitializeComponent();varmyListBox=newMyListBox();内容=我的列表框;myListBox.Items.Add(newButton(){Content="abc"});myListBox.Items.Add(newButton(){Content="abc"});myListBox.Items.Add(newButton(){Content="abc"});myListBox.Items.Add(newButton(){Content="abc"});myListBox.Items.Add(newButton(){Content="abc"});varbutton=newButton(){Content="检查ScrollViewer"};button.Click+=(s,e)=>{if(myListBox.ScrollViewer==null)Console.WriteLine("null");};myListBox.Items.Add(按钮);}}}当我单击“检查ScrollViewer”按钮时,它会打印“null”。即,未检查到ScrollViewer。我如何找到令人信服的ScrollViewer??如果您将使用标准的ListBox,那么您可以将getter更改为:publicclassMyListBox:ListBox{publicSc??rollViewerScrollViewer{get{Borderborder=(Border)VisualTreeHelper.GetChild(this,0);返回(ScrollViewer)VisualTreeHelper.GetChild(border,0);你可以试试这个小辅助函数用法varscrollViewer=GetDescendantByType(yourListBox,typeof(ScrollViewer))asScrollViewer;辅助函数publicstaticVisualGetDescendantByType(Visualelement,Typetype){if(element==null){returnnull;}if(element.GetType()==type){返回元素;}VisualfoundElement=null;if(elementisFrameworkElement){(elementasFrameworkElement).ApplyTemplate();}for(inti=0;我希望这有助于我修改@punker76的优秀答案,为具有显式返回类型的Visual创建扩展方法:publicstaticclassExtensions{publicstaticTGetDescendantByType(thisVisualelement)whereT:class{if(element==null){returndefault(T);}if(element.GetType()==typeof(T)){返回元素t为T;}TfoundElement=null;if(elementisFrameworkElement){(elementasFrameworkElement).ApplyTemplate();}for(vari=0;i();if(foundElement!=null){break;}}returnfoundElement;}}你现在可以通过SomeVisual.GetDescendantByType调用它,它返回一个已经是正确类型的ScrollViewer或者null(默认为(T))对于我来说,首先将ScrollViewer作为属性公开是一个坏主意,不能保证ScrollViewer存在于模板中。其次,ScrollViewer与ItemsPanel和ItemContainerGenerator同步工作。重写这是一种不常见行为的直接方式。WPF控件使用另一种模式。它们的类就像外部逻辑使用和内部视觉呈现之间的中介。ListBox应该公开ScrollViewer可以在模板中使用的属性,而不是ScrollViewer。通过做这样一来,您就违反了WPF标准,将控制限制在特定模板中,并允许用户代码破解内部ListBox实现。这是@punker76对C#6的另一个重写和通用版本:以上是C#学习教程分享的全部内容:ScrollViewerAccessingListBoxfromC#,如果对大家有用,需要进一步了解C#学习教程,希望你多注意---publicstaticclassVisualExtensions{publicstaticTFindVisualDescendant(thisVisualelement)whereT:Visual{if(element==null)returnnull;vare=元素作为T;如果(e!=null)返回e;(作为FrameworkElement的元素)?.ApplyTemplate();varchildrenCount=VisualTreeHelper.GetChildrenCount(元素);for(vari=0;i();if(foundElement!=null)returnfoundElement;}returnnull;}}本文收集自网络,不代表立场,如涉及侵权,请点击有权联系管理员删除,如有转载请注明出处: