如何通过ViewModel调用自定义控件上的方法

时间:2013-11-29 15:26:41

标签: c# wpf mvvm viewmodel

我在我的项目中使用MVVM模式。它使用了代码隐藏。

我遇到的问题是:我的项目中包含了从Simple WPF Page transitions下载的页面转换控件。


它在代码隐藏方面效果很好,xaml如下:

<Grid ShowGridLines="False">
    <pageTransitions:PageTransition Name="pageTransitionControl" Margin="0" TransitionType="GrowAndFade" />
</Grid>

在窗口标记中显示:

xmlns:pageTransitions="clr-namespace:WpfPageTransitions;assembly=WpfPageTransitions" 


在代码隐藏中我刚刚运行:

mast.Page mp = new mast.Page();
pageTransitionControl.ShowPage(mp);

当我执行下面的代码隐藏时,它会卸载当前页面(mp)并加载新的(dp)

dist.Page dp = new dist.Page();
pageTransitionControl.ShowPage(dp);

以上“mp”和“dp”是UserControl(页面)的新实例。 pageTransitionControl是xaml中转换控件的名称。

现在我想让它通过ViewModel运行,而不像上面那样与视图通信,我该如何解决这个问题呢?

1 个答案:

答案 0 :(得分:3)

理想情况下,PageTransition控件将为您提供通过绑定设置当前页面的方法。假设它没有提供这样做的方法,那么有很多方法可以实现这一点。

以下是三个建议,按照“好看”的顺序(在我看来)。

  1. 您可以创建一个新的页面转换控件,它可以是PageTransition的包装器,也可以继承它。然后将当前页面的DependecyProperty添加到您可以绑定到的类,捕获dependecy属性更改事件并调用ShowPage

  2. 根据使用情况编写一个继承FrameworkElementDependencyObject的类,该类可以绑定到页面和PageTransition控件。然后,当当前页面发生更改时,此类负责在绑定的ShowPage控件上调用PageTransition

  3. PageTransition控件绑定到模型上的属性,并让模型中的代码通过该属性访问控件。

  4. 示例:

    public class MyPageTransition : ContentControl
    {
        public static readonly DependencyProperty CurrentPageProperty = 
            DependencyProperty.Register(
                "CurrentPage", 
                typeof(object), 
                typeof(MyPageTransition), 
                new PropertyMetadata(DependencyPropertyChanged));
    
        public ContentControl()
        {
            this.Content = this.pageTransition;
        }
    
        public object CurrentPage
        {
            get { return GetValue(CurrentPageProperty); }
            set { SetValue(CurrentPageProperty, value); }
        }
    
        protected static void DependencyPropertyChanged(
            DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.Property == CurrentPageProperty)
            {
                this.pageTransition.ShowPage(CurrentPage);
            }
        }
    
        private PageTransition pageTransition = new PageTransition();
    }
    
相关问题