我在循环中努力使用XAML变量,我的问题详述如下:
我有一个foreach()
循环,我在XAML中有4张图片叫做image1, image2, image3, image4
,现在我想将一张图片与我联系起来。我的foreach循环中的路径到每个image
变量。
一个明显的解决方案是:
foreach() {
//my stuff
image1.Source = bitmapSource;
image2.Source = bitmapSource;
image3.Source = bitmapSource;
image4.Source = bitmapSource;
}
但是这个解决方案并不灵活,我考虑将我的image
变量放在一个数组中,但我不认为这是可能的(至少我还没有发现任何内容)办法)。
最好/最干净的方法是什么?感谢
答案 0 :(得分:1)
使用LINQ和Enumerable.OfType<TResult> Method
:
Grid1.Children.OfType<Image>().ToList().ForEach(c => c.Source = bitmapSource);
我假设图像位于Grid
容器内,名称为Grid1
。如果它们在另一个容器内,则相应地改变。
修改强> 如果您的图像位于上一个评论中指出的不同容器内,则可以执行此操作:
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj)
where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
然后:
FindVisualChildren<Image>(MainGrid).ToList().ForEach(c => c.Source = bitmapSource);
我再次假设您的不同容器位于名为Grid
的主MainGrid
内。