我有这个项目,我想通过将自定义控件(inSignalLight)添加到列表框(或其他一些控件,我只想将它们排列起来)来为我的屏幕设置一些图像。我已经在自定义控件中设置了图像并将它们添加到“ObservableCollection”中,但没有显示任何内容。我对 WPF 真的很陌生,所以不太确定 xaml 是否正确......如果有更好的方法可以在列表框中执行此操作,请也告诉我。
inSignalLights = new ObservableCollection<inSignalLight>();
这是我想在其中显示图片的页面中的 xaml。
<Page x:Class="Project.Pages.MainPicView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Background="Beige"
Title="MainPicView" d:DesignHeight="343" d:DesignWidth="676">
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Label Content="Label" Height="30" HorizontalAlignment="Left" Margin="61,195,0,0" Name="label1" VerticalAlignment="Top" Width="164" />
<ListBox ItemsSource="{Binding Path=inSignalLights}" Width="400" Height="25" Margin="0,0,0,0" VerticalAlignment="Top" HorizontalAlignment="Left">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</Grid>
</Page>
编辑:
这是自定义控件的 xaml
<UserControl x:Class="Project.CustomControls.inSignalLight"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="16" d:DesignWidth="16">
<Grid>
<Image Height="16" HorizontalAlignment="Left" Margin="0,0,0,0" Name="signalImage" Stretch="Fill" VerticalAlignment="Top" Width="16" />
</Grid>
</UserControl>
编辑:
for (int i = 0; i < inpins; i++)
{
InPin ip = iFace.getInPin(i);
parent.insertNewSignalLight(ip);
}
public void insertNewSignalLight(InPin ip)
{
inSignalLight isl = new inSignalLight(ip);
isl.setLightOff();
this.inSignalLights.Add(isl.signalImage);
}
public void setLightOff()
{
setThreadSafeImage(signalImage);
}
private void gotLightSignal(InPin pin, EventArgs e)
{
Thread.CurrentThread.Join(200);
if (pin.PinState == 1)
setLightOn();
else
setLightOff();
}
public void setThreadSafeImage(Image iS)
{
string strUri2 = String.Format(@"pack://application:,,,/;component/Images/Signal_Gron_16.png");
BitmapImage img = new BitmapImage(new Uri(strUri2));
img.Freeze();
iS.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => iS.Source = img));
}