這裏是一個解決方案,
視圖模型:
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>
希望這會起作用
這完全沒有必要。不要解析一段XAML,你也可以編程方式創建UI元素。或者甚至更好,向視圖模型添加與佈局相關的屬性,並使用帶有適當的ItemsPanel和ItemContainerStyle的ItemsControl,它們綁定到視圖模型屬性。 – Clemens
只需創建一個自定義UserControl即可從ViewModel中獲取圖像並處理所有佈局。在ViewModel中創建UI不是MVVM。 – Will