我在画布中创建形状(矩形,椭圆,线条)。然后我在另一个窗口中有一个listview,我需要输入形状的信息(如位置,大小,形状)。
我在另一个窗口的XAML中有这段代码:
<ListView Name="Information">
<ListView.View>
<GridView>
<GridViewColumn Header="Type"/>
<GridViewColumn Header="PositionX"/>
<GridViewColumn Header="PositionY"/>
<GridViewColumn Header="Width" DisplayMemberBinding="{Binding ActualWidth}"/>
<GridViewColumn Header="Height" DisplayMemberBinding="{Binding ActualHeight}"/>
</GridView>
</ListView.View>
</ListView>
在主窗口的c#中,我有一个可观察的集合和这段代码:
ObservableCollection<Shape> shapes = new ObservableCollection<Shape>();
myRect.Width = var1;
myRect.Height = var2;
Page.Children.Add(myRect);
Canvas.SetLeft(myRect, posx);
Canvas.SetTop(myRect, posy);
shapes.Add(myRect);
2ndwindow.Information.ItemsSource = shapes; // this is working because the 2ndwindow is owned by the mainwindow
编辑:我设法绑定宽度和高度,但我不知道如何绑定位置和形状(矩形或椭圆)
答案 0 :(得分:2)
在适当的MVVM方法中,你应该有一个带有Shape的抽象表示的视图模型(而不是UI元素列表),例如:像这样:
public class ShapeData
{
public string Type { get; set; }
public Geometry Geometry { get; set; }
public Brush Fill { get; set; }
public Brush Stroke { get; set; }
public double StrokeThickness { get; set; }
}
public class ViewModel
{
public ObservableCollection<ShapeData> Shapes { get; }
= new ObservableCollection<ShapeData>();
}
您现在可以将此视图模型绑定到如下所示的视图。从形状对象的Bounds
的{{1}}属性中检索每个形状的位置和大小。
Geometry
您可以在窗口的构造函数中创建一个视图模型实例,并添加一些示例数据:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ItemsControl ItemsSource="{Binding Shapes}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Path Data="{Binding Geometry}"
Fill="{Binding Fill}"
Stroke="{Binding Stroke}"
StrokeThickness="{Binding StrokeThickness}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ListView Grid.Column="1" ItemsSource="{Binding Shapes}">
<ListView.View>
<GridView>
<GridViewColumn Header="Type"
DisplayMemberBinding="{Binding Type}"/>
<GridViewColumn Header="X"
DisplayMemberBinding="{Binding Geometry.Bounds.X}"/>
<GridViewColumn Header="Y"
DisplayMemberBinding="{Binding Geometry.Bounds.Y}"/>
<GridViewColumn Header="Width"
DisplayMemberBinding="{Binding Geometry.Bounds.Width}"/>
<GridViewColumn Header="Height"
DisplayMemberBinding="{Binding Geometry.Bounds.Height}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>