2016-12-02 69 views
-3

我根據所獲取的數據創建了具有多行和兩列的Grid。現在我有一個Xaml字符串。如何在加載時在我的用戶控件中呈現。必須從我的viewmodel渲染。如何做到這一點。?如何在用戶控件WPF MVVM中呈現動態Xaml字符串?

真實場景,

我會從數據庫中接收一些圖像。必須在每一行中顯示兩個圖像。但我不能創建行數不變。因爲它將基於動態數據。如果數據是10我必須創建5行,更少意味着行也會減少。

因此,我打算根據數據在Viewmodel中創建xaml。但是如何在我的用戶控件中呈現它。

+0

這完全沒有必要。不要解析一段XAML,你也可以編程方式創建UI元素。或者甚至更好,向視圖模型添加與佈局相關的屬性,並使用帶有適當的ItemsPanel和ItemContainerStyle的ItemsControl,它們綁定到視圖模型屬性。 – Clemens

+0

只需創建一個自定義UserControl即可從ViewModel中獲取圖像並處理所有佈局。在ViewModel中創建UI不是MVVM。 – Will

回答

2

這裏是一個解決方案,

視圖模型:

public class ViewModel : PropertyChangedMonitor 
    { 
     ObservableCollection<ImageModel> _imageList; 
     public ViewModel() 
     { 
      _imageList = new ObservableCollection<ImageModel>(); 
      ImageList.Add(new ImageModel { ImageName = "/ImageLoad;component/Images/1.png" }); 
      ImageList.Add(new ImageModel { ImageName = "/ImageLoad;component/Images/2.png" }); 
      ImageList.Add(new ImageModel { ImageName = "/ImageLoad;component/Images/3.png" }); 
      ImageList.Add(new ImageModel { ImageName = "/ImageLoad;component/Images/4.png" }); 
      ImageList.Add(new ImageModel { ImageName = "/ImageLoad;component/Images/5.png" }); 
      Columns = 2; 
     } 



     public ObservableCollection<ImageModel> ImageList 
     { 
      get 
      { 
       return _imageList; 
      } 

     } 


     private int _column; 

     public int Columns 
     { 
      get 
      { 
       return _column; 
      } 
      set 
      { 
       if (_column != value) 
       { 
        _column = value; 
        OnPropertyChanged("Columns"); 
       } 

      } 
     } 
    } 

圖像模型類:

public class ImageModel 
    { 
     public string ImageName { get; set; } 
    } 

和用戶控制:

<UserControl x:Class="ImageLoad.ImageDisplay" 
      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:local="clr-namespace:ImageLoad" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:vm="clr-namespace:ImageLoad" 
      d:DesignHeight="300" 
      d:DesignWidth="300" 
      mc:Ignorable="d"> 
    <UserControl.DataContext> 
     <vm:ViewModel /> 
    </UserControl.DataContext> 
    <Grid> 
     <ItemsControl ItemsSource="{Binding ImageList}"> 
      <ItemsControl.ItemsPanel> 
       <ItemsPanelTemplate> 
        <UniformGrid Columns="{Binding Columns, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> 
       </ItemsPanelTemplate> 
      </ItemsControl.ItemsPanel> 
      <ItemsControl.ItemTemplate> 
       <DataTemplate> 
        <Image Source="{Binding ImageName}" /> 
       </DataTemplate> 
      </ItemsControl.ItemTemplate> 
     </ItemsControl> 
    </Grid> 
</UserControl> 

希望這會起作用

+0

謝謝@MANIKANDAN NAGALAKSHMI。有用。 –