Connect FrameworkElement to MVVM
Somethimes it necessary in MVVM to knowing FrameworkElement for setting something
I have create an helper for getting this FrameworkElement in MVVM
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public static class ControlHelper { #region ConnectToMVVM public static object GetConnectToMVVM(DependencyObject obj) => (object)obj.GetValue(ConnectToMVVMProperty); public static void SetConnectToMVVM(DependencyObject obj, object value) => obj.SetValue(ConnectToMVVMProperty, value); public static readonly DependencyProperty ConnectToMVVMProperty = DependencyProperty.RegisterAttached("ConnectToMVVM", typeof(object), typeof(ControlHelper), new FrameworkPropertyMetadata(new object(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault ,(ss,ee) => { SetConnectToMVVM(ss, ss); } )); #endregion } |
and used in mvvm like this
1 2 3 4 5 6 7 8 9 10 11 12 |
#region ControlRef private object _ControlRef = new object(); public object ControlRef { get => _ControlRef; set { _ControlRef = value; OnPropertyChanged(); } } #endregion |
and in xaml
1 2 3 4 5 6 |
<Border Margin="2" Background="White" BorderBrush="gray" BorderThickness="1" ucwpfhelper:ControlHelper.ConnectToMVVM="{Binding ControlRef}"> ...... |
and for sample to create an picture set in clipboard
1 2 3 4 5 6 7 |
if (ControlRef is FrameworkElement fe) { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap( (int)fe.ActualWidth, (int)fe.ActualHeight, 96, 96, PixelFormats.Pbgra32); renderTargetBitmap.Render(fe); Clipboard.SetImage(renderTargetBitmap); } |
Categories: Non classé
Commentaires récents