[英]Accessing a public method from a class inside a SurfaceListBox
我已經創建了WPF解決方案,如https://msdn.microsoft.com/en-us/library/ff727730.aspx所述 。 該解決方案將使用SurfaceListBox
為我提供連續列表。 一切正常,沒有問題。
現在,我想單擊圖像並向任意方向移動X像素。
因此,我創建了事件MainSurfaceListBox_OnSelectionChanged
並將其添加到MainWindow.xaml
:
<Window x:Class="ContinuousList.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="http://schemas.microsoft.com/surface/2008"
xmlns:l="clr-namespace:ContinuousList"
Title="ContinuousList" Height="640" Width="800">
<Grid>
<s:SurfaceListBox Name="MainSurfaceListBox"
SelectionChanged="MainSurfaceListBox_OnSelectionChanged">
<s:SurfaceListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}" Width="270"/>
</DataTemplate>
</s:SurfaceListBox.ItemTemplate>
<s:SurfaceListBox.Template>
<ControlTemplate>
<s:SurfaceScrollViewer
VerticalScrollBarVisibility="Disabled"
HorizontalScrollBarVisibility="Hidden"
CanContentScroll="true">
<l:LoopPanelVertical IsItemsHost="True"/>
</s:SurfaceScrollViewer>
</ControlTemplate>
</s:SurfaceListBox.Template>
</s:SurfaceListBox>
</Grid>
</Window>
在MainWindow.xaml.cs
private void MainSurfaceListBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
//trying to call a public method from LoopPanelVertical
}
現在,從MainWindow.xaml.cs
我正在嘗試運行方法LoopPanelVertical.LineUp()
。 我的問題是我找不到從LoopPanelVertical
訪問此方法或任何公共方法的方法。
namespace ContinuousList
{
public class LoopPanelVertical : Panel, ISurfaceScrollInfo
{
...
public void LineUp()
{
ScrollContent(1);
}
}
}
請幫助我了解實現此目標的必要條件嗎? 謝謝!
為了調用(非靜態)類的方法,您需要引用該類的實例。 您可以設置LoopPanelVertical
類的Name
或x:Name
屬性,然后使用該名稱引用它:
<ControlTemplate>
<s:SurfaceScrollViewer
VerticalScrollBarVisibility="Disabled"
HorizontalScrollBarVisibility="Hidden"
CanContentScroll="true">
<l:LoopPanelVertical x:Name="Panel" IsItemsHost="True"/>
</s:SurfaceScrollViewer>
</ControlTemplate>
...
private void MainSurfaceListBox_OnSelectionChanged(object sender,
SelectionChangedEventArgs e)
{
Panel.LineUp();
}
剛剛使用child元素找到了答案:
private void MainSurfaceListBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listBox = sender as SurfaceListBox;
if (listBox == null) return;
var childElement = FindChild(listBox, i => i as LoopPanelVertical);
childElement.LineUp();
}
static T FindChild<T>(DependencyObject obj, Func<DependencyObject, T> pred) where T : class
{
var childrenCount = VisualTreeHelper.GetChildrenCount(obj);
for (var i = 0; i < childrenCount; i++)
{
var dependencyObject = VisualTreeHelper.GetChild(obj, i);
var foo = pred(dependencyObject);
return foo ?? FindChild(dependencyObject, pred);
}
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.