I have a problem plotting a collection of lines into a canvas. Google showed me several sources but i couldn't find a real solution for this one. I hope you guys have a hint for me.
My stucture is as follows:
public class CanvasLine
{
public Double X1 { get; set; }
public Double X2 { get; set; }
public Double Y1 { get; set; }
public Double Y2 { get; set; }
public Brush StrokeColor { get; set; }
public Double StrokeThickness { get; set; }
public DoubleCollection StrokeDashArray { get; set; }
}
public class CanvasObject
{
public String Name { get; set; }
public ObservableCollection<CanvasLine> CanvasLines { get; set; }
}
public class ViewModel
{
...
public ObservableCollection<CanvasObject> CanvasObjects;
...
}
XAML:
<Window x:Class="XXX.Views.MainWindow"
xmlns:vm="clr-namespace:XXX.Viewmodels"
xmlns:converter="clr-namespace:XXX.Converter"
Title="XXX" Height="480" Width="640">
<Window.DataContext>
<vm:ViewModel/>
</Window.DataContext>
<Grid>
<ItemsControl Grid.Column="1" Grid.Row="2" Margin="0" ItemsSource="{Binding CanvasObjects, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Line DataContext="{Binding CanvasLines}" Stroke="{Binding StrokeColor}" StrokeDashArray="{Binding StrokeDashArray}" StrokeThickness="{Binding StrokeThickness}">
<Line.X1>
<MultiBinding Converter="{StaticResource MultiplicationConverter}">
<Binding Path="X1"/>
<Binding Path="ActualWidth" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Canvas}"/>
</MultiBinding>
</Line.X1>
<Line.X2>
<MultiBinding Converter="{StaticResource MultiplicationConverter}">
<Binding Path="X2"/>
<Binding Path="ActualWidth" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Canvas}"/>
</MultiBinding>
</Line.X2>
<Line.Y1>
<MultiBinding Converter="{StaticResource MultiplicationConverter}">
<Binding Path="Y1"/>
<Binding Path="ActualWidth" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Canvas}"/>
</MultiBinding>
</Line.Y1>
<Line.Y2>
<MultiBinding Converter="{StaticResource MultiplicationConverter}">
<Binding Path="Y2"/>
<Binding Path="ActualWidth" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Canvas}"/>
</MultiBinding>
</Line.Y2>
</Line>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
This is for demonstration, i might have deleted too much.
My problem is that only the first CanvasLine
for each CanvasObject
is shown in the canvas. It works fine if i give up the CanvasObject
and the DataContext="{Binding CanvasLines}"
and directly bind the ItemsControl
to a ObservableCollection<CanvasLine>
but in the next steps i need to add more objects and also i'm trying to avoid a huge list of lines an to keep some kind of object structure.
Since i'm pretty new to this MVVM Binding stuff i'm happy about any thoughts you like to share.
Greetings.