C
C#2y ago
binstarjs

❔ WPF binding expression of property from ItemsControl item with viewmodel property

Lets say I need to draw list of circles in WPF using ItemsControl and put it in Canvas so i can position each individual circles freely. Each circle has position property, that is the actual position of the circle. Then in my viewmodel, i have PositionOffset property that whatever the Canvas item position should be offsetted by that. For example i have a circle at position (5,2) and my viewmodel PositionOffset is (10,10), then i want that circle to be positioned at (15,12) in the canvas of ItemsControl. So yes, this means in my itemscontrol.itemtemplate, when i need to set the property of Canvas.Left etc, i need to do something like {Binding Position.X + PositionOffset.X}. How do i do this? Below is the example of the code.
public class CircleModel
{
public Point Position { get; set; }
public Brush Color { get; set; }
}

public class WindowViewModel
{
public Point PositionOffset { get; set; }
public ObservableCollection<CircleModel> Circles = new();
}
public class CircleModel
{
public Point Position { get; set; }
public Brush Color { get; set; }
}

public class WindowViewModel
{
public Point PositionOffset { get; set; }
public ObservableCollection<CircleModel> Circles = new();
}
<ItemsControl ItemsSource="{Binding Circles}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Width="512" Height="512" Fill="{Binding Color}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<!--HOW TO OFFSET X AND Y BY "WindowViewModel.PositionOffset"!? Below is definitely NOT syntatically correct-->
<Setter Property="Canvas.Left" Value="{Binding Position.X + PositionOffset.X}"/>
<Setter Property="Canvas.Top" Value="{Binding Position.Y + PositionOffset.Y}"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
<ItemsControl ItemsSource="{Binding Circles}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Width="512" Height="512" Fill="{Binding Color}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<!--HOW TO OFFSET X AND Y BY "WindowViewModel.PositionOffset"!? Below is definitely NOT syntatically correct-->
<Setter Property="Canvas.Left" Value="{Binding Position.X + PositionOffset.X}"/>
<Setter Property="Canvas.Top" Value="{Binding Position.Y + PositionOffset.Y}"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
1 Reply
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.