我需要将对象数组 Image
绑定(bind)到 WrapPanel。
我在主类构造函数中声明了对象:
public MainWindow()
{
InitializeComponent();
private Masina[] _masina = new Masina[12];
DataContext = new
{
data1 = _masina
};
}
我的类 Masina
里面有几个变量,但我只想绑定(bind) Image
:
public class Masina
{
public Image masina_pav = new Image();
public bool r_mas;
public string s_mas;
public Masina()
{
byte[] buffer = File.ReadAllBytes("teksturos/masinos/red/top.png");
MemoryStream memoryStream = new MemoryStream(buffer);
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.DecodePixelWidth = 100;
bitmap.DecodePixelHeight = 200;
bitmap.StreamSource = memoryStream;
bitmap.EndInit();
bitmap.Freeze();
masina_pav.Source = bitmap;
Canvas.SetLeft(masina_pav, 100);
Canvas.SetTop(masina_pav, 200);
}
}
我试过这个 XAML 代码:
<WrapPanel Name="zem" Height="1000" Width="1108" >
<ItemsControl ItemsSource="{Binding data1}" DisplayMemberPath="masina_pav">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Name="masinu_sarasas" HorizontalAlignment="Center" IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</WrapPanel >
For now program starts but don't show me any
Image
(should be 12 of them). Can someone help me to figure it out ?
最佳答案
Image
是不应在 View 模型中使用的 View 类。相反,您的类应该提供类型为 ImageSource
的公共(public)属性。请注意,它是一个属性,而不是您声明的字段。这是必要的,因为 WPF 数据绑定(bind)仅适用于公共(public)属性。
public class Masina
{
public ImageSource MasinaPav { get; private set; }
...
public Masina()
{
using (var fileStream = new FileStream(
"teksturos/masinos/red/top.png",
FileMode.Open, FileAccess.Read, FileShare.Read))
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.DecodePixelWidth = 100;
bitmap.DecodePixelHeight = 200;
bitmap.StreamSource = fileStream;
bitmap.EndInit();
bitmap.Freeze();
MasinaPav = bitmap;
}
}
}
现在你的 ItemsControl 将有一个 ItemTemplate
和一个绑定(bind)到 View 模型属性的图像控件:
<ItemsControl ItemsSource="{Binding data1}">
...
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding MasinaPav}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
除此之外,同时设置 BitmapImage 的 DecodePixelWidth
和 DecodePixelHeight
时要小心,因为它可能会破坏位图的纵横比。
关于c# - 使用 ItemsControl 绑定(bind)对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36801696/