【问题标题】:Delete all images added to canvas删除添加到画布的所有图像
【发布时间】:2012-06-05 20:05:58
【问题描述】:

有没有可能的方法来移除(删除)添加到 C#(在 WFP 中)中的 Canvas 的所有图像(子图像)?

【问题讨论】:

    标签: c# .net wpf image wpf-controls


    【解决方案1】:

    由于 Canvas 的子集合是 UIElementCollection 并且有很多其他控件使用这种类型的集合,我们可以通过扩展方法为所有控件添加 remove 方法。

    public static class CanvasExtensions
    {
        /// <summary>
        /// Removes all instances of a type of object from the children collection.
        /// </summary>
        /// <typeparam name="T">The type of object you want to remove.</typeparam>
        /// <param name="targetCollection">A reference to the canvas you want items removed from.</param>
        public static void Remove<T>(this UIElementCollection targetCollection)
        {
            // This will loop to the end of the children collection.
            int index = 0;
    
            // Loop over every element in the children collection.
            while (index < targetCollection.Count)
            {
                // Remove the item if it's of type T
                if (targetCollection[index] is T)
                    targetCollection.RemoveAt(index);
                else
                    index++;
            }
        }
    }
    

    当此类存在时,您可以简单地使用该行删除所有图像(或任何其他类型的对象)。

    testCanvas.Children.Remove<Image>();
    

    【讨论】:

      【解决方案2】:

      你的意思是你只想删除所有的子元素?

      canvas.Children.Clear();
      

      看起来应该可以完成这项工作。

      编辑:如果您想要删除Image 元素,您可以使用:

      var images = canvas.Children.OfType<Image>().ToList();
      foreach (var image in images)
      {
          canvas.Children.Remove(image);
      }
      

      这假设所有图像都是 直接 子元素 - 如果你想删除其他元素下的 Image 元素,它变得更加棘手。

      【讨论】:

        猜你喜欢
        • 2016-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-19
        • 2020-07-02
        • 1970-01-01
        • 2016-04-21
        • 1970-01-01
        相关资源
        最近更新 更多