2017-03-20 52 views
0

我在WPF一個ContentControl中,它在它如何添加圖像和文本塊到WPF ContentControl中

ContentControl myContentControl = new ContentControl(); 
myContentControl.Content = image; 

圖像如何旁邊添加一個文本塊到ContentControl中內的圖像? 謝謝。

+0

不是直接添加圖像,而是先添加水平方向的堆疊面板,然後添加圖像和文本塊。 –

回答

1

你在做什麼樣子你不熟悉MVVM: 請檢查here

簡單的解決方案

但是,如果你想要的醜陋的解決方案,並在你的代碼中創建UIElement小號的背後 - 是這樣的:

public static ContentControl CreateControl(string title, Uri path) 
    { 
     //Create your image 
     BitmapImage bitmapImage = new BitmapImage(path); 
     Image image = new Image() 
     { 
      Source = bitmapImage 
     }; 

     //Create your Text 
     TextBlock textB = new TextBlock() 
     { 
      Text = title 
     }; 

     //Put them together 
     StackPanel content = new StackPanel(); 
     content.Children.Add(image); 
     content.Children.Add(textB); 

     //Add this to the content control 
     return new ContentControl() 
     { 
      Content = content 
     }; 

    } 
+0

謝謝。我將研究MVVM鏈接。 – khuang

1

您需要更改ContentControl中的財產ContentTemplate,爲ContentTemplate,這裏是一些解釋:

獲取或設置用於顯示ContentControl中的內容的數據模板。

而且你需要創建一個類來表示你的數據,這樣的:

public class ImageInfo 
{ 
    public string Caption { get; set; } 
    public ImageSource Image { get; set; } 
} 

最好是在XAML創建ContentControl,像這樣:

<ContentControl x:Name="cc"> 
     <ContentControl.ContentTemplate> 
      <DataTemplate> 
       <StackPanel> 
        <Image Source="{Binding Image}" /> 
        <TextBlock Text="{Binding Caption}" /> 
       </StackPanel> 
      </DataTemplate> 
     </ContentControl.ContentTemplate> 
    </ContentControl> 

然後,分配數據到ContentControl:

cc.Content = new ImageInfo() { Caption = "Hello", Image = new BitmapImage(new System.Uri("/Assets/User.jpg", UriKind.Relative)) }; 
+0

謝謝。我需要動態添加這些內容控件,例如能夠通過用戶點擊按鈕添加和刪除內容控件。我幾乎全部都是從後臺完成的。雖然將數據綁定到xmal聽起來更好,但如何實現? – khuang

相關問題