c# - 在 ViewModel 中访问 XAML 对象

标签 c# wpf xaml mvvm modal-dialog

如何访问我的 ViewModel 中的 XAML 对象?我真的很困惑。我想访问 <Controls:ModalContentPresenter>目的。我怎么能以符合 MVVM 的方式实现这一点?我想在这个对象上调用一个方法 ShowModalContent

<Controls:ModalContentPresenter x:Name="modalContent">
    <ScrollViewer Behaviors:AdvancedZooming.KeepInCenter="true" Visibility="{Binding LeerformularIsVisible}" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
        <Viewbox Stretch="Uniform">
            <Grid>
                <DataGrid BorderBrush="{x:Null}">
                    <DataGrid.ContextMenu>
                        <ContextMenu>
                            <MenuItem Command="{Binding AddFieldDefinitionCommand}" Header="Feld hinterlegen" Icon="pack://application:,,,/Images/Designer/field.png" />
                            <MenuItem Command="{Binding AddFunctionCommand}" Header="Funktion hinterlegen" Icon="pack://application:,,,/Images/Designer/FI_Taschenmesser_16x16.png" />
                            <MenuItem Command="{Binding RemoveFieldDefinitionCommand}" Header="Aktuelle Felddefinition entfernen" Icon="pack://application:,,,/Images/Designer/remove_field.png" />
                            <MenuItem Command="{Binding CutCommand}" Header="Ausschneiden" Icon="pack://application:,,,/Images/Zwischenablage/FI_Ausschneiden_16x16.png" />
                            <MenuItem Command="{Binding CopyCommand}" Header="Kopieren" Icon="pack://application:,,,/Images/Zwischenablage/FI_Kopieren_16x16.png" />
                            <MenuItem Command="{Binding PasteCommand}" Header="Einfügen" Icon="pack://application:,,,/Images/Zwischenablage/FI_Einfuegen_16x16.png" />
                        </ContextMenu>
                    </DataGrid.ContextMenu>

                </DataGrid>
            </Grid>

        </Viewbox>

    </ScrollViewer>

    <Controls:ModalContentPresenter.ModalContent>
        <StackPanel>
            <TextBlock>Test</TextBlock>
            <Button>Hide</Button>
        </StackPanel>
    </Controls:ModalContentPresenter.ModalContent>
</Controls:ModalContentPresenter>

ModalContentPresenter 的代码可以在这里找到:

using System;
using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;

namespace Controls
{
    [ContentProperty("Content")]
    public class ModalContentPresenter : FrameworkElement
    {
        #region private fields
        private Panel layoutRoot;
        private ContentPresenter primaryContentPresenter;
        private ContentPresenter modalContentPresenter;
        private Border overlay;
        private object[] logicalChildren;
        private KeyboardNavigationMode cachedKeyboardNavigationMode;
        private static readonly TraversalRequest traversalDirection;
        #endregion

        #region dependency properties
        public static readonly DependencyProperty IsModalProperty = DependencyProperty.Register("IsModal", typeof(bool), typeof(ModalContentPresenter),
            new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsModalChanged));

        public static readonly DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(object), typeof(ModalContentPresenter),
        new UIPropertyMetadata(null, OnContentChanged));

        public static readonly DependencyProperty ModalContentProperty = DependencyProperty.Register("ModalContent", typeof(object), typeof(ModalContentPresenter),
        new UIPropertyMetadata(null, OnModalContentChanged));

        public static readonly DependencyProperty OverlayBrushProperty = DependencyProperty.Register("OverlayBrush", typeof(Brush), typeof(ModalContentPresenter), 
        new UIPropertyMetadata(new SolidColorBrush(Color.FromArgb(204, 169, 169, 169)), OnOverlayBrushChanged));

        public bool IsModal
        {
            get { return (bool)GetValue(IsModalProperty); }
            set { SetValue(IsModalProperty, value); }
        }

        public object Content
        {
            get { return (object)GetValue(ContentProperty); }
            set { SetValue(ContentProperty, value); }
        }

        public object ModalContent
        {
            get { return (object)GetValue(ModalContentProperty); }
            set { SetValue(ModalContentProperty, value); }
        }

        public Brush OverlayBrush
        {
            get { return (Brush)GetValue(OverlayBrushProperty); }
            set { SetValue(OverlayBrushProperty, value); }
        } 
        #endregion

        #region routed events
        public static readonly RoutedEvent PreviewModalContentShownEvent = EventManager.RegisterRoutedEvent("PreviewModalContentShown", RoutingStrategy.Tunnel,
        typeof(RoutedEventArgs), typeof(ModalContentPresenter));

        public static readonly RoutedEvent ModalContentShownEvent = EventManager.RegisterRoutedEvent("ModalContentShown", RoutingStrategy.Bubble,
        typeof(RoutedEventArgs), typeof(ModalContentPresenter));

        public static readonly RoutedEvent PreviewModalContentHiddenEvent = EventManager.RegisterRoutedEvent("PreviewModalContentHidden", RoutingStrategy.Tunnel, 
        typeof(RoutedEventArgs), typeof(ModalContentPresenter));

        public static readonly RoutedEvent ModalContentHiddenEvent = EventManager.RegisterRoutedEvent("ModalContentHidden",  RoutingStrategy.Bubble, 
        typeof(RoutedEventArgs), typeof(ModalContentPresenter));

        public event RoutedEventHandler PreviewModalContentShown
        {
            add { AddHandler(PreviewModalContentShownEvent, value); }
            remove { RemoveHandler(PreviewModalContentShownEvent, value); }
        }

        public event RoutedEventHandler ModalContentShown
        {
            add { AddHandler(ModalContentShownEvent, value); }
            remove { RemoveHandler(ModalContentShownEvent, value); }
        }

        public event RoutedEventHandler PreviewModalContentHidden
        {
            add { AddHandler(PreviewModalContentHiddenEvent, value); }
            remove { RemoveHandler(PreviewModalContentHiddenEvent, value); }
        }

        public event RoutedEventHandler ModalContentHidden
        {
            add { AddHandler(ModalContentHiddenEvent, value); }
            remove { RemoveHandler(ModalContentHiddenEvent, value); }
        }
        #endregion

        #region ModalContentPresenter implementation
        static ModalContentPresenter()
        {
            traversalDirection = new TraversalRequest(FocusNavigationDirection.First);
        }

        public ModalContentPresenter()
        {
            layoutRoot = new ModalContentPresenterPanel();
            primaryContentPresenter = new ContentPresenter();
            modalContentPresenter = new ContentPresenter();
            overlay = new Border();

            AddVisualChild(layoutRoot);

            logicalChildren = new object[2];

            overlay.Background = OverlayBrush;
            overlay.Child = modalContentPresenter;
            overlay.Visibility = Visibility.Hidden;

            layoutRoot.Children.Add(primaryContentPresenter);
            layoutRoot.Children.Add(overlay);
        }

        public void ShowModalContent()
        {
            if (!IsModal)
                IsModal = true;
        }

        public void HideModalContent()
        {
            if (IsModal)
                IsModal = false;
        }

        private void RaiseModalContentShownEvents()
        {
            RoutedEventArgs args = new RoutedEventArgs(PreviewModalContentShownEvent);
            OnPreviewModalContentShown(args);
            if (!args.Handled)
            {
                args = new RoutedEventArgs(ModalContentShownEvent);
                OnModalContentShown(args);
            }
        }

        private void RaiseModalContentHiddenEvents()
        {
            RoutedEventArgs args = new RoutedEventArgs(PreviewModalContentHiddenEvent);
            OnPreviewModalContentHidden(args);
            if (!args.Handled)
            {
                args = new RoutedEventArgs(ModalContentHiddenEvent);
                OnModalContentHidden(args);
            }
        }

        protected virtual void OnPreviewModalContentShown(RoutedEventArgs e)
        {
            RaiseEvent(e);
        }

        protected virtual void OnModalContentShown(RoutedEventArgs e)
        {
            RaiseEvent(e);
        }

        protected virtual void OnPreviewModalContentHidden(RoutedEventArgs e)
        {
            RaiseEvent(e);
        }

        protected virtual void OnModalContentHidden(RoutedEventArgs e)
        {
            RaiseEvent(e);
        }
        #endregion

        #region property changed callbacks
        private static void OnIsModalChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ModalContentPresenter control = (ModalContentPresenter)d;

            if ((bool)e.NewValue == true)
            {
                control.cachedKeyboardNavigationMode = KeyboardNavigation.GetTabNavigation(control.primaryContentPresenter);
                KeyboardNavigation.SetTabNavigation(control.primaryContentPresenter, KeyboardNavigationMode.None);

                control.overlay.Visibility = Visibility.Visible;
                control.overlay.MoveFocus(traversalDirection);

                control.RaiseModalContentShownEvents();
            }
            else
            {
                control.overlay.Visibility = Visibility.Hidden;

                KeyboardNavigation.SetTabNavigation(control.primaryContentPresenter, control.cachedKeyboardNavigationMode);
                control.primaryContentPresenter.MoveFocus(traversalDirection);

                control.RaiseModalContentHiddenEvents();
            }
        }

        private static void OnContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ModalContentPresenter control = (ModalContentPresenter)d;

            if (e.OldValue != null)
                control.RemoveLogicalChild(e.OldValue);

            control.primaryContentPresenter.Content = e.NewValue;
            control.AddLogicalChild(e.NewValue);
            control.logicalChildren[0] = e.NewValue;
        }

        private static void OnModalContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ModalContentPresenter control = (ModalContentPresenter)d;

            if (e.OldValue != null)
                control.RemoveLogicalChild(e.OldValue);

            control.modalContentPresenter.Content = e.NewValue;
            control.AddLogicalChild(e.NewValue);
            control.logicalChildren[1] = e.NewValue;
        }

        private static void OnOverlayBrushChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ModalContentPresenter control = (ModalContentPresenter)d;
            control.overlay.Background = (Brush)e.NewValue;
        }
        #endregion

        #region FrameworkElement overrides
        protected override Visual GetVisualChild(int index)
        {
            if (index < 0 || index > 1)
                throw new ArgumentOutOfRangeException("index");

            return layoutRoot;
        }

        protected override int VisualChildrenCount
        {
            get { return 1; }
        }

        protected override IEnumerator LogicalChildren
        {
            get { return logicalChildren.GetEnumerator(); }
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            layoutRoot.Arrange(new Rect(finalSize));
            return finalSize;
        }

        protected override Size MeasureOverride(Size availableSize)
        {
            layoutRoot.Measure(availableSize);
            return layoutRoot.DesiredSize;
        }
        #endregion

        #region layout panel
        class ModalContentPresenterPanel : Panel
        {
            protected override Size MeasureOverride(Size availableSize)
            {
                Size resultSize = new Size(0, 0);

                foreach (UIElement child in Children)
                {
                    child.Measure(availableSize);
                    resultSize.Width = Math.Max(resultSize.Width, child.DesiredSize.Width);
                    resultSize.Height = Math.Max(resultSize.Height, child.DesiredSize.Height);
                }

                return resultSize;
            }

            protected override Size ArrangeOverride(Size finalSize)
            {
                foreach (UIElement child in InternalChildren)
                {
                    child.Arrange(new Rect(finalSize));
                }

                return finalSize;
            }
        }
        #endregion
    }
}

最佳答案

你不应该这样做(至少,这绝对不是 MVVM 方式)。
改为使用 IsModal 属性和数据绑定(bind):

<Controls:ModalContentPresenter x:Name="modalContent" IsModal="{Binding IsModal}">

绑定(bind)表达式中的 IsModal 是 View 模型中的绑定(bind)数据属性。

关于c# - 在 ViewModel 中访问 XAML 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25119470/

相关文章:

c# - 是否存在在 XAML 中使用任意 C# 表达式的现有方法?

WPF:自定义控件属性已被另一个自定义控件错误注册

C# 使方法更通用以供重用,有没有更好的方法?

c#:Monitor.Wait是如何实现的?

c# - 如何在 ListView 的组标题中保存 IsExpanded 状态

c# - .net 4.0 的 "Modern UI (Metro) Charts for Windows 8, WPF, Silverlight"

c# - 从 C# 调用 wstring C++ 方法

c# - 带有 APNS sharp 的苹果推送通知

c# - OxyPlot,不在 LineSeries 中的点

wpf - 有没有安全的方法来分离/卸载行为而没有副作用?