[英]How to bind a shape's properties to a business model's properties
我有一個代表用戶顯示的畫布。 在畫布上,您可以繪制和調整代表屏幕各部分的矩形的大小。
我有一個名為Section的模型。 我的視圖模型中有它們的集合。
我想以某種方式綁定和自動創建/更新List<Section>
每次繪制或更新矩形(調整大小/刪除)。
我的Section.cs看起來像這樣。
public class Section
{
public int SectionId { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int X { get; set; }
public int Y { get; set; }
public SectionType SectionType { get; set; }
[ForeignKey("Layout")]
public int LayoutId { get; set; }
[ForeignKey("LayoutId")]
public virtual Layout Layout { get; set; }
}
因此,實際上我希望發生以下情況:
新增部分:
現有部分
我不知道如何將一個矩形綁定到一個節,以便它們被鏈接。 當用戶選擇前不久創建的Rectangle時,代碼應自動知道要更新哪個Section。
非常感謝您提供有關如何以最佳實踐解決此問題的正確方向的任何指示。
在ViewModel中創建Section類型對象的ObservableCollection。
ObservableCollection<Section> _col;
public ObservableCollection<Section> Sections
{
get { return _col; }
set
{
_col = value;
OnPropertyChanged("Sections");
}
}
並將其綁定到您的XAML中,如下所示
<ItemsControl Name="itemsControl" ItemsSource="{Binding Path=Sections}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="White" Width="500" Height="500" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Fill="Red" Width="{Binding Width}" Height="{Binding Height}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Top" Value="{Binding Path=Y}" />
<Setter Property="Canvas.Left" Value="{Binding Path=X}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.