Add n rectangles to canvas with MVVM in WPF

前端 未结 2 1750
轻奢々
轻奢々 2020-11-22 02:39

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.Recta

2条回答
  •  温柔的废话
    2020-11-22 02:58

    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 RectItems { get; set; }
    }
    

    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:

    
        
            
                
            
        
        
            
        
        
            
                
            
        
    
    

    An alternative without Bindings in Style Setters (which don't work in UWP) might look like this:

    
        
            
                
            
        
        
            
                
                    
                        
                    
                
            
        
    
    

提交回复
热议问题