【问题标题】:Adding controls dynamically in xaml window store app with events attached?在附加事件的xaml窗口商店应用程序中动态添加控件?
【发布时间】:2014-05-11 14:41:39
【问题描述】:

我有一个画布,里面有一个图像控件,其中包含事件 ManipulationDelta 事件、单击事件等。 我有一个添加按钮,可以将图像控件添加到画布

Image image = new Image();
            string url = "ms-appx:///Assets/992829_484663934955807_859212711_n.jpg";
            BitmapImage bm = new BitmapImage();

            bm.UriSource = new Uri(url, UriKind.Absolute);
            image.Source = bm;
            image.Height = 100;
            image.Width = 100;

            MyCanvas.Children.Add(image);

现在我想为这个控件和许多其他动态创建相同的事件,以便它们有自己的 ManipulationDelta 和 Click 事件。如何做到这一点?我应该使用匿名方法、Lambda 表达式等吗?只是一个指导我的提示??

【问题讨论】:

    标签: c# xaml windows-store-apps windows-8.1


    【解决方案1】:

    像这样订阅事件

    image.ManipulationDelta += image_ManipulationDelta;
    image.Tapped += image_Tapped;
    
    
    void image_Tapped(object sender, TappedRoutedEventArgs e)
    {
        //do something
    }
    
    void image_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
    {
        //do somthing
    }
    

    在 Visual Studio 中 .. 只需键入 image.ManipulationDelta +=,然后按 Tab 2 次。它会自动创建事件处理方法

    您也可以使用匿名方法创建事件处理程序

    image.ManipulationDelta += (sender, e) =>
    {
        //do something
    };
    

    【讨论】:

    • 但我不知道用户将添加多少控件,所以这仅适用于一个假设我添加了 10 个图像我想拖动它们、旋转等它们都有自己的事件,我现在没有它们都是在runime制作的??
    • 如果您希望图像控件在事件触发时执行相同的行为。只需将它们订阅到事件处理程序即可。在这种情况下,事件处理程序将为每个图像控件进行平移、旋转。但是,如果您想对特定控件进行某些操作。您可以使用事件处理程序中的“sender”参数检查哪个控件触发了事件。例如 var image = (Image)sender;
    • 是否有任何文档或示例?
    • 相同的事件调用但来自不同的控件?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    相关资源
    最近更新 更多