I have been trying to create a list of triangles for a while now, to do this I inherited a ListBoxItem and gave them a polygon. But unfortunately the triangle is not shown to me in any way and I don't understand why it doesn't work.
This is the code I currently have: Once the PolygonItem for the triangle, a list of the PolygonItems in a ViewModel and the XAML code to display that, first directly in the MainWindow.
public ObservableCollection<PolygonItem> PolygonItems { get; set; }
public MainViewModel() {
PolygonItems = new ObservableCollection<PolygonItem>() {
new PolygonItem
{
Polygon = new Polygon
{
Width = 100,
Height = 100,
Points = new PointCollection
{
new Point(40, 40),
new Point(100, 40),
new Point(70, 100),
}
}
},
};
}
public class PolygonItem: ListBoxItem
{
public Polygon Polygon { get; set; }
}
public class PointCollectionConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value is PointCollection points)
{
return string.Join(" ", points.Select(p => $"{p.X},{p.Y}"));
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string pointsString)
{
var pointsArray = pointsString.Split(' ');
var pointCollection = new PointCollection();
foreach(var point in pointsArray)
{
var pointsValues = point.Split(',');
if(pointsValues.Length == 2
&& double.TryParse(pointsValues[0], out var x)
&& double.TryParse(pointsValues[1], out var y))
{
pointCollection.Add(new System.Windows.Point(x, y));
}
}
return pointCollection;
}
return null;
}
}
<Grid>
<ListBox ItemsSource="{Binding PolygonItems}" Width="300" Height="300">
<ListBox.ItemTemplate>
<DataTemplate>
<Polygon Points="{Binding Path=Polygon.Points,
Converter={StaticResource PointCollectionConverter}}"
Stroke="Black" Fill="Aquamarine">
</Polygon>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>