将事件处理程序添加到单独的ResourceDictionary文件中的模板中的ItemsControl项

时间:2013-09-22 05:15:27

标签: c# wpf xaml windows-phone

我有一个电话申请页面(Main.xaml),其中包含ItemsControl及其项目的数据模板。

<phone:PhoneApplicationPage.Resources>
    <local:MainItemsViewModel x:Key="mainItems" />
    <DataTemplate x:Key="ItemTemplate">
        <Grid Tap="Item_Tap"> 
            <!--....--> 
        </Grid>  
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>   

<!--...a lot of xaml...-->

<ItemsControl
       x:Name="MainCanvas"
       DataContext="{StaticResource mapItems}"
       ItemsSource="{Binding Path=Buttons}"
       ItemTemplate="{StaticResource ItemTemplate}">
       <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                  <Canvas Width="4000" Height="4000" />
            </ItemsPanelTemplate>
       </ItemsControl.ItemsPanel>
</ItemsControl>

如上所示,DataTemplate有一个事件处理程序,它在代码隐藏文件(MainPage.xaml.cs)中定义:

private void Item_Tap(object sender, System.Windows.Input.GestureEventArgs e) 
{
     FrameworkElement fe = sender as FrameworkElement;
     //working with fe...

     ApplicationBar.IsVisible = true; 
     e.Handled = true;
}   

一切都很完美。但我想将数据模板移动到单独的ResourceDictionary文件(ResDict.xaml)。当然,我收到错误,因为现在无法触发Item_Tap事件处理程序。是否可以在ResourceDictionary中包含一个调用Item_Tap方法的事件处理程序?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。可能它不是最好的,但它对我有用。 在页面构造函数中,我为LayoutUpdate事件添加了一个事件处理程序:

MainCanvas.LayoutUpdated += MainCanvas_LayoutUpdated;

在这个事件处理程序(MainCanvas_LayoutUpdated)中,我调用一个包含以下代码的方法:

foreach (var item in MainCanvas.Items)
{
        DependencyObject icg = MainCanvas.ItemContainerGenerator.ContainerFromItem(item);
        (icg as FrameworkElement).Tap += MainItem_Tap;
}

它在itemsource控件(MainCanvas)中的所有项目的事件处理程序绑定后,其itemsource更改并且项目显示在Canvas中。

可能会对某人有所帮助。谢谢!