我想在我的mvvm应用程序的主窗口中添加一组矩形.在我的viewModel中,我有一个对象集合,我用转换器转换为System.Windows.Shapes.Rectangle类(代码如下):
视图模型:
RecognizedValueViewModel
{
public ObservableCollection<BarcodeElement> BarcodeElements
{
get { return _BarcodeElements; }
set { _BarcodeElements = value; }
}
public RecognizedValueViewModel()
{
BarcodeElements = InitializeBarcodeElements();
}
}
Run Code Online (Sandbox Code Playgroud)
转换器:
public BarcodeElementToRectangleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Rectangle barcodeRectangle = GetRectangleFromBarcodeElement(value as BarcodeElement);
return barcodeRectangle;
}
}
Run Code Online (Sandbox Code Playgroud)
矩形应显示在MainWindow的画布中:
<Canvas x:Name="Canvas_Image_Main">
<!-- Show rectangles here -->
</Canvas>
Run Code Online (Sandbox Code Playgroud)
我会在代码中将Rectangles添加到canvas中,但我现在还没有在运行时有多少个矩形.我有办法实现这个目标吗?保护你.
我希望能够实现带有可拖动项目的ItemsControl.ItemsControl的原因是我可以在后台绑定到我的ViewModel.
我尝试在画布中使用Thumb控件,它工作得很完美,除非我将它粘在ItemsControl中它就会停止工作.这是我尝试过的:
<ItemsControl ItemsSource="{Binding MyItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Thumb Canvas.Left="0" Canvas.Top="0" Width="50" Height="50" DragDelta="MyThumb_DragDelta"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)
背后的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
private void MyThumb_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
Canvas.SetLeft((UIElement)sender, Canvas.GetLeft((UIElement)sender) + e.HorizontalChange);
Canvas.SetTop((UIElement)sender, Canvas.GetTop((UIElement)sender) + e.VerticalChange);
}
Run Code Online (Sandbox Code Playgroud)
最后我的ViewModel:
public class MainViewModel : DependencyObject
{
public ObservableCollection<Note> MyItems { get; set;}
public MainViewModel()
{
MyItems = new ObservableCollection<Note>();
MyItems.Add(new Note(){Name="test"});
}
}
public …Run Code Online (Sandbox Code Playgroud)