2016-12-16 33 views
-5

我在窗口上有一些圖像,我怎樣才能在它們周圍環繞它們以將圖像設置爲cover.jpg通過WPF窗口上的圖像控件進行Foreach循環

public partial class MainWindow : Window 
{ 
    int score; 
    List<int> lst = new List<int>(); 

    public MainWindow() 
    { 
     InitializeComponent(); 
     foreach(Image img in Grid.) 
    }   
} 
+0

你在哪裏存儲你的圖像?什麼是「網格」?它是一個控件嗎? – FCin

+0

你有什麼嘗試?你有例外嗎?或者已經在工作的東西,但不是正確的方式?順便說一句,看看這裏:http://stackoverflow.com/help/how-to-ask – gobes

+0

是的,它的WPF應用程序 – Jazab

回答

0

我建議不要在後面的代碼中這樣做,而是使用MVVM的原則,並使用綁定到ImagesList的ItemSource的GridView/ListView(您必須使其成爲ObservableCollection而不是列表)。如果您需要更多數據,請將圖像封裝在包含所需附加數據的類中。 這種方式你不需要循環,一切都發生在它自己的「

0

檢查以下問題。

WPF: How do I loop through the all controls in a window?

你應該能夠做到這一點是這樣的:

public MainWindow() 
{ 
InitializeComponent(); 

IEnumerable<Image> images = GetChildren(Grid).OfType<Image>(); 
if (images != null) 
{ 
    BitmapImage bi = new BitmapImage(new Uri("pic.png", UriKind.Relative)); 
    foreach (Image image in images) 
    { 
     image.Source = bi; 
    } 
    } 
} 

public static IEnumerable<Visual> GetChildren(Visual parent, bool recurse = true) 
{ 
    if (parent != null) 
    { 
     int count = VisualTreeHelper.GetChildrenCount(parent); 
     for (int i = 0; i < count; i++) 
     { 
     // Retrieve child visual at specified index value. 
     var child = VisualTreeHelper.GetChild(parent, i) as Visual; 

     if (child != null) 
     { 
      yield return child; 

      if (recurse) 
      { 
       foreach (var grandChild in GetChildren(child, true)) 
       { 
        yield return grandChild; 
       } 
      } 
      } 
     } 
    } 
    } 

<Window x:Class="WpfApplication1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:local="clr-namespace:WpfApplication1" 
    mc:Ignorable="d" 
    Title="MainWindow" Height="300" Width="300"> 
<Grid x:Name="Grid"> 
<Image ... /> 
.... 
0

代碼隱藏 code behind Desginer designer 據SA我的理解,這是什麼您需要將硬編碼位置更改爲您的海灣r.jpg。

+0

環控制顯示沒有錯誤,但得到錯誤,並退出。 – Jazab

+0

完成。感謝您的建議。 – Jazab