循环访问子元素,查找内容并访问其兄弟属性

时间:2013-05-12 08:09:31

标签: c# wpf linq

我有WrapPanel,其中包含一些图像(缩略图)。

当用户按左或右箭头键时,我想显示下一张/上一张图像。

private void frmMain_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Right)
    {
        int j = 0;
        foreach (Image child in WrapPanelPictures.Children)
        {
            if (child.Source == MainPic.Source)
            {
                MainPic.Source = WrapPanelPictures.Children[j + 1].Source;
            }
            j++;
        }
    }
}

我也尝试过LINQ方法,但我是LINQ的初学者。

var imgfound = from r in WrapPanelPictures.Children.OfType<Image>()
               where r.Source == MainPic.Source
               select r;
MessageBox.Show(imgfound.Source.ToString());

imgfound应该是一个列表,对吗?也许这就是我无法访问Source属性的原因。无论如何,这将返回当前显示的图像。我想要兄弟姐妹。

更新: 好吧,我现在做了一个解决方法。但仍在等待正确的解决方案。

我创建了一个ListBox并添加了所有WrapPanel Childrens。然后使用SelectedItemSelectedIndex属性选择上一个和下一个项目。

4 个答案:

答案 0 :(得分:3)

由于您尝试访问WrapPanelPictures.Children[j + 1].Source不存在的Source属性,UIElement无效。在访问UIElement

之前,您应该将Source转换为图片
MainPic.Source = (WrapPanelPictures.Children[j + 1] as Image).Source;

我相信有更优雅的解决方案可以获得相同的结果。

答案 1 :(得分:1)

你得到了诺维奇无法访问Source属性的答案。不过我会建议您重新考虑您的代码。

我看到它的方式,你可以控制你的包装面板显示的内容。这意味着您应该能够将“所有图像”以及所选索引存储在字段或属性中。不是每次解析你的包装面板的孩子的图像和比较图像源,你应该知道你选择的图像或索引是什么。

然后代码可能大致如下:

private List<BitmapImage> _images;
private int _selectedIndex;

private void frmMain_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Right)
    {
        _selectedIndex = (_selectedIndex + 1) % _images.Count;
        MainPic.Source = _images[_selectedIndex];
    }
}

如果你的UI是高度动态的(将图像拖放到包装面板或类似的东西中),使用Bindings将数据与UI链接是可行的方法。在任何情况下,我也强烈建议考虑像MVVM一样的ViewModel模式。

答案 2 :(得分:0)

使用方法FindVisualChildren。它遍历Visual Tree并找到您想要的控件。

这应该可以解决问题

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 != null && child is T)
        {
            yield return (T)child;
        }

        foreach (T childOfChild in FindVisualChildren<T>(child))
        {
            yield return childOfChild;
        }
    }
}
}

然后你枚举像这样的控件

foreach (TextBlock tb in FindVisualChildren<TextBlock>(window))
{
    // do something with tb here
}

答案 3 :(得分:0)

不要在foreach循环中声明j。否则,这将始终显示j=0 WrapPanelPictures.Children[1]

的图像
    private void frmMain_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Right)
        {
           int j = 0;
           foreach (Image child in WrapPanelPictures.Children)
           {
                // int j = 0;
                if (child.Source == MainPic.Source)
                {
                    MainPic.Source = WrapPanelPictures.Children[j + 1].Source;
                    break;
                }
                j++;
            }
        }
    }