2012-02-15 109 views
1

我試着做了一下WPF的,只有等到真正做到窗口形式,而不是現在好多說......動態創建的按鈕在WPF

所有我想要做的是動態內代碼(不是xaml)設置一個按鈕來顯示圖像,並將按鈕的大小設置爲圖像的自動調整大小。

下面的代碼加載圖像,但它會在鼠標位於按鈕上方並且該按鈕不會自動調整圖像大小時執行。

tbButtonPicture在PC上包含一個本地路徑到一個位圖,例如, C:\temp\my Artwork\test1.bmp

這是我有迄今它在一個循環內位於:

Console.WriteLine(tbButtonPicture); 
System.Windows.Controls.Button newBtn = new Button(); 
//newBtn.Content = i.ToString(); 
newBtn.Background = new ImageBrush(new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), tbButtonPicture))); 
newBtn.Name = "Button" + i.ToString(); 
sp.Children.Add(newBtn); 

i++; 
+0

對不起Nemesv,我已經更新了一個問題! – Adrian 2012-02-15 12:05:08

+3

爲什麼不添加一些'ItemsControl'派生類並將其綁定到數據容器? – 2012-02-15 12:05:57

+0

嗨,謝爾,謝謝你的建議,但我不知道我該怎麼做!我會google的ItemsControl。當你在winforms中設置一個屬性時,它更容易:(我認爲即使這個簡單的任務也給了我很多新的東西來傾斜... – Adrian 2012-02-15 12:12:58

回答

2

裹在Image控件圖像並將其設置爲按鈕的內容,你應該有你想要的效果。

System.Windows.Controls.Button newBtn = new Button(); 
    Image imageControl = new Image(); 
    imageControl.Source = new BitmapImage(new Uri(BaseUriHelper.GetBaseUri(this), tbButtonPicture)); 
    newBtn.Content = imageControl; 
    newBtn.Name = "Button" + i.ToString(); 
    sp.Children.Add(newBtn); 

    i++; 

但我完全上述評論一致認爲: 試圖解決在XAML您的問題更容易。閱讀建議的資源,他們真的很有幫助。

+0

謝謝你已經得到它的工作。 – Adrian 2012-02-15 13:47:20