2012-01-07 6 views
0

複数のボタンを表示する必要がありますが、それぞれが別のボタンとは異なる背景を持っていなければなりませんが、複数のボタンを表示するだけです同じ背景。ここで はXAMLです:WPFの複数のボタンで異なる背景を表示するには

<Window x:Class="apple.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="370" Width="525"> 
    <Grid> 
     <Image Source="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg" Stretch="Fill"/> 
     <DockPanel Name="dock"> 
      <UniformGrid Name="gridx" DockPanel.Dock="Top" Rows="3" Columns="3" Height="334"> 
      </UniformGrid> 
     </DockPanel> 
    </Grid> 
</Window> 

また、ここではC#のコードは次のとおりです。

namespace apple 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      masterGUI(); 
     } 

    public void masterGUI() 
    { 
     ImageBrush ib = new ImageBrush(); 
     IconImage[] ico = null; 
     Bitmap[] img = null; 
     string[] list = null; 
     string[] link = Directory.GetFiles(@"C:\ProgramData\Microsoft\Windows\Start Menu\Programs", "*.lnk", SearchOption.AllDirectories); 
     list = new string[link.Length]; 
     ico = new Icon[link.Length]; 
     img = new Bitmap[link.Length]; 
     for (int n = 0; n < link.Length; n++) 
     { 
      System.Windows.Controls.Button newBtn = new Button(); 
      list[n] = System.IO.Path.GetFileNameWithoutExtension(link[n]); 
      FileToImageIconConverter some = new FileToImageIconConverter(link[n]); 
      ImageSource imgSource = some.Icon; 
      ib.ImageSource = imgSource; 
      newBtn.Background = ib; 
      newBtn.Content = list[n]; 
      gridx.Children.Add(newBtn); 
     } 
    } 
} 

}

任意のアイデア?ありがとうございました。

答えて

1

ImageBrushは、for-loopで各項目ごとに個別に作成する必要があります。さもなければ、あなたはすべてのアイテムのために同じ背景に終わるでしょう。

また、これは「間違った」方法に近づいています.WPFでは、命令型ループではなく、data bindingdata templatingをこの種類のものに使用する必要があります。

+0

ありがとうございます!各ボタンに異なるアクションを実行させる方法はありますか? –

+1

@FernandoSantiago:はい、画像をホストクラスと[コマンド](http://msdn.microsoft.com/en-us/library/ms752308.aspx)を作成し、それぞれ、それらに結合するいずれか(これはクリーンである)、または条件に応じて['Click'イベント](http://msdn.microsoft.com/en-us/library/system.windows.controls.button.aspx)をフックします。 –

+0

もう一度ありがとう、私はそれに取り組む! –

関連する問題