加正矩形与MVVM在WPF以帆布 [英] Add n rectangles to canvas with MVVM in WPF
问题描述
我想一组矩形添加到我的MVVM应用程序的主窗口。在我的ViewModel我有对象的集合,我转换为System.Windows.Shapes.Rectangle类用转换器(code以下):
I want to add a set of rectangles to the main window of my mvvm application. In my viewModel I've got a collection of objects which I convert to System.Windows.Shapes.Rectangle classes with a converter (code below):
视图模型:
RecognizedValueViewModel
{
public ObservableCollection<BarcodeElement> BarcodeElements
{
get { return _BarcodeElements; }
set { _BarcodeElements = value; }
}
public RecognizedValueViewModel()
{
BarcodeElements = InitializeBarcodeElements();
}
}
转换器:
public BarcodeElementToRectangleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Rectangle barcodeRectangle = GetRectangleFromBarcodeElement(value as BarcodeElement);
return barcodeRectangle;
}
}
该矩形应显示在画布在我的主窗口:
The rectangles should be shown in a canvas in my MainWindow:
<Canvas x:Name="Canvas_Image_Main">
<!-- Show rectangles here -->
</Canvas>
我想补充的矩形code到画布,但我现在有多少矩形在运行时有没有没有。有没有一种方法,我怎么能做到这一点?坦克你。
I would add Rectangles to canvas in code but I don't now how many rectangles are there at runtime. Is there a way how I can achieve this? Tank you.
推荐答案
在一个适当的MVVM方法,你将有矩形列表,例如一个抽象的重presentation视图模型像这样的:
In a proper MVVM approach you would have a view model with an abstract representation of a list of rectangles, e.g. like this:
public class RectItem
{
public double X { get; set; }
public double Y { get; set; }
public double Width { get; set; }
public double Height { get; set; }
}
public class ViewModel
{
public ObservableCollection<RectItem> RectItems { get; set; }
}
然后,你将不得不使用一个ItemsControl想象这样的矩形
项目集合的视图。 ItemsControl的将有一个画布作为其 ItemsPanel
和适当的 ItemContainerStyle
和的ItemTemplate
,每个绑定到相应的视图模型属性。它可能是这样的:
Then you would have a view that uses an ItemsControl to visualize a collection of such Rect
items. The ItemsControl would have a Canvas as its ItemsPanel
and an appropriate ItemContainerStyle
and ItemTemplate
which each bind to the appropriate view model properties. It might look like this:
<ItemsControl ItemsSource="{Binding RectItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding X}"/>
<Setter Property="Canvas.Top" Value="{Binding Y}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Rectangle Width="{Binding Width}" Height="{Binding Height}" Fill="Black"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
这篇关于加正矩形与MVVM在WPF以帆布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!