Pushing read-only GUI properties back into ViewModel

后端 未结 6 1881
攒了一身酷
攒了一身酷 2020-11-22 12:50

I want to write a ViewModel that always knows the current state of some read-only dependency properties from the View.

Specifically, my GUI contains a FlowDocumentPa

6条回答
  •  一向
    一向 (楼主)
    2020-11-22 13:29

    I use a universal solution which works not only with ActualWidth and ActualHeight, but also with any data you can bind to at least in reading mode.

    The markup looks like this, provided ViewportWidth and ViewportHeight are properties of the view model

    
        
             
                 
                 
              
         
    
    

    Here is the source code for the custom elements

    public class DataPiping
    {
        #region DataPipes (Attached DependencyProperty)
    
        public static readonly DependencyProperty DataPipesProperty =
            DependencyProperty.RegisterAttached("DataPipes",
            typeof(DataPipeCollection),
            typeof(DataPiping),
            new UIPropertyMetadata(null));
    
        public static void SetDataPipes(DependencyObject o, DataPipeCollection value)
        {
            o.SetValue(DataPipesProperty, value);
        }
    
        public static DataPipeCollection GetDataPipes(DependencyObject o)
        {
            return (DataPipeCollection)o.GetValue(DataPipesProperty);
        }
    
        #endregion
    }
    
    public class DataPipeCollection : FreezableCollection
    {
    
    }
    
    public class DataPipe : Freezable
    {
        #region Source (DependencyProperty)
    
        public object Source
        {
            get { return (object)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(object), typeof(DataPipe),
            new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnSourceChanged)));
    
        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((DataPipe)d).OnSourceChanged(e);
        }
    
        protected virtual void OnSourceChanged(DependencyPropertyChangedEventArgs e)
        {
            Target = e.NewValue;
        }
    
        #endregion
    
        #region Target (DependencyProperty)
    
        public object Target
        {
            get { return (object)GetValue(TargetProperty); }
            set { SetValue(TargetProperty, value); }
        }
        public static readonly DependencyProperty TargetProperty =
            DependencyProperty.Register("Target", typeof(object), typeof(DataPipe),
            new FrameworkPropertyMetadata(null));
    
        #endregion
    
        protected override Freezable CreateInstanceCore()
        {
            return new DataPipe();
        }
    }
    

提交回复
热议问题