Skip to main content
 首页 » 编程设计

c#之Silverlight、DataTemplate、绑定(bind)到点击事件

2024年08月12日39落叶

你好,

我在这里变得绝望了。考虑以下用例。

我有一个列表框,其中的项目是自定义模板化控件。它有几个按钮,这个自定义控件在代码后面有事件处理程序。每当单击按钮时,我都会调用我的自定义控件通过 DataContext 绑定(bind)到的对象的方法。因此,当用户单击停止时,我调用 _context.stopDownload() 并由对象完成其余的工作。

但是,我只有一个按钮可以开始播放内容。我试图以某种方式在核心级别上收听此按钮的单击事件,而不是在代表列表框项目 UI 的自定义控件的代码后面。

总结一下:

  1. 我有一个核心对象,它将项目列表加载到可观察集合中。
  2. 此核心对象然后使用 GetTemplateChildnren 获取列表框对象。完成后,核心将列表框控件的 ItemsSource 设置为我在#1 步骤中获得的可观察集合。列表框使用自定义模板控件作为其项目呈现(使用 DataTemplate)。
  3. 我需要将核心对象级别的事件处理程序链接到 DataTemplate 内自定义控件的按钮元素。

我想不通#3。除其他事项外,我在设置 ItemsSource 以连接事件处理程序后尝试执行类似的操作,但容器始终为 null。

DownloadsListElement.ItemsSource = _downloadsList; 
 
foreach (var item in DownloadsListElement.ItemsSource) 
{ 
    var container = DownloadsListElement.ItemContainerGenerator.ContainerFromItem(item) as     FrameworkElement; 
} 

我还尝试在列表框上按一个网格,并尝试在 Grid 的 MouseLeftButtonDown/Up 上使用 VisualTreeHelper 单击按钮,但是当我单击按钮时,这些按钮永远不会被调用。

我认为唯一可能的解决方案是当我在某个全局对象中注册事件处理程序然后从 DataTemplate 内的自定义控件调用它时使用某种命令模式。

我没有想法,希望有人有类似的问题。

谢谢。

更新

感谢 McGamagle 和 ChrisW,我让它工作了。我在按钮上的最终代码如下所示:

<i:Interaction.Triggers> 
    <i:EventTrigger EventName="Click"> 
        <ei:CallMethodAction TargetObject="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType=local:ListBoxExt}}" MethodName="PlayButton_Click"/> 
    </i:EventTrigger> 
</i:Interaction.Triggers> 

谢谢大家!

请您参考如下方法:

我的理解是,您想将处理程序附加到列表框项目的 DataTemplate 内的项目,其中处理程序属于父级的 DataContext。

您可以使用 RelativeSource FindAncestor 绑定(bind)来做到这一点。您可能想考虑使用 ICommand 而不是处理程序,但如果您确实需要处理程序,则可以使用 Blend SDK 的 CallMethodAction .

XAML 应该看起来像这样(其中“SomeCommand”是 ListBox 数据上下文的 ICommand 属性):

<ListBox> 
    <ListBox.ItemTemplate> 
        <DataTemplate> 
            <Button Command="{Binding RelativeSource={RelativeSource AncestorType=ListBox}, 
                                      Path=DataContext.SomeCommand}" /> 
        </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

或者使用“CallMethodAction”技术(此处“HandleButtonClick”必须是 ListBox 数据上下文的公共(public)方法):

<ListBox> 
    <ListBox.ItemTemplate> 
        <DataTemplate> 
            <Button> 
                <i:Interaction.Triggers> 
                    <i:EventTrigger EventName="Click"> 
                        <ei:CallMethodAction  
                            TargetObject="{Binding RelativeSource={RelativeSource AncestorType=ListBox}, Path=DataContext.SomeCommand}"  
                            MethodName="HandleButtonClick" /> 
                    </i:EventTrigger EventName="Click"> 
                </i:Interaction.Triggers> 
            </Button> 
        </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox>