【问题标题】:Binding WPF button contained in a usercontrol, with its own viewmodel, to a function in the mainwindow viewmodel将用户控件中包含的 WPF 按钮及其自己的视图模型绑定到主窗口视图模型中的函数
【发布时间】:2017-06-09 19:34:03
【问题描述】:

我有一个简单的窗口,里面有一个用户控件“NewCardView”。取消按钮需要调用包含在 MainWindow 的视图模型中的函数才能切换当前显示的 UserControl。当我按下按钮时,它什么也不做,什么都没有追踪,就像它没有绑定任何东西一样。我尝试绑定到该窗口的数据上下文,但没有成功。

 <UserControl x:Class="MapProject.View.NewCardView"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 xmlns:local="clr-namespace:MapProject.MainView.View"
                 xmlns:mainwin="clr-namespace:MapProject"
                 mc:Ignorable="d" 
                 d:DesignHeight="300" d:DesignWidth="300">
        <Grid>
            <Label x:Name="labeltitle" Content="New Card" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,10,0,0"/>
            <ComboBox x:Name="comboBox" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" Margin="133,43,0,0"/>
            <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="133,74,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="120"/>
            <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="23" Margin="133,105,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="120"/>
            <DatePicker HorizontalAlignment="Left" VerticalAlignment="Top" Margin="133,136,0,0" Width="120"/>
            <Label x:Name="label" Content="District" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="62,43,0,0"/>
            <Label x:Name="label1" Content="Map #" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="62,74,0,0"/>
            <Label x:Name="label2" Content="Parcel #" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="62,105,0,0"/>
            <Label x:Name="label3" Content="Date From" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="62,136,0,0"/>
            <Button x:Name="button" Content="OK" HorizontalAlignment="Left" Margin="78,184,0,0" VerticalAlignment="Top" Width="75"/>
            <Button x:Name="button_Copy" Content="Cancel" CommandParameter="Blank" Command="{Binding DataContext.ChangePageCommand, BindsDirectlyToSource=True, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type mainwin:MainWindow}}}" HorizontalAlignment="Left" Margin="178,184,0,0" VerticalAlignment="Top" Width="75"/>

        </Grid>

    public ICommand ChangePageCommand
    {
        get
        {
            if (_changePageCommand == null)
            {
                _changePageCommand = new RelayCommand(p => ChangeViewModel(p.ToString()), p => p is string);
            }

            return _changePageCommand;
        }

}

MainWindow 包含这个

<DataTemplate DataType="{x:Type mainviewviewmodel:NewCardViewModel}">
    <mainview:NewCardView/>
</DataTemplate>

using System;
using System.Diagnostics;
using System.Windows.Input;

    namespace MapProject
    {
        /// <summary>
        /// A command whose sole purpose is to 
        /// relay its functionality to other
        /// objects by invoking delegates. The
        /// default return value for the CanExecute
        /// method is 'true'.
        /// </summary>
        public class RelayCommand : ICommand
        {
            #region Fields

            readonly Action<object> _execute;
            readonly Predicate<object> _canExecute;

            #endregion // Fields

            #region Constructors

            /// <summary>
            /// Creates a new command that can always execute.
            /// </summary>
            /// <param name="execute">The execution logic.</param>
            public RelayCommand(Action<object> execute)
                : this(execute, null)
            {
            }

            /// <summary>
            /// Creates a new command.
            /// </summary>
            /// <param name="execute">The execution logic.</param>
            /// <param name="canExecute">The execution status logic.</param>
            public RelayCommand(Action<object> execute, Predicate<object> canExecute)
            {
                if (execute == null)
                    throw new ArgumentNullException("execute");

                _execute = execute;
                _canExecute = canExecute;
            }

            #endregion // Constructors

            #region ICommand Members

            [DebuggerStepThrough]
            public bool CanExecute(object parameters)
            {
                return _canExecute == null ? true : _canExecute(parameters);
            }

            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }

            public void Execute(object parameters)
            {
                _execute(parameters);
            }

            #endregion // ICommand Members
        }
    }

【问题讨论】:

  • 尽管您说“具有自己的视图模型的用户控件”,但您的代码看起来不像用户控件实际上会有自己的视图模型。而且它不应该有一个。所以命令绑定可以简单地是Command="{Binding ChangePageCommand}"。请注意,除非绑定到 DataSourceProvider,否则设置 BindsDirectlyToSource 无效。
  • 我添加了我认为是 MainSearch 中包含的作业。我已经尝试过您的建议,但我相信当我分配它时它处于不同的数据上下文中。你能解释一下为什么它不应该有自己的视图模型吗?
  • ChangePageCommand 应该在 NewCardViewModel 中。
  • 那么它将如何与我的主窗口进行通信?控制显示哪个用户控件的对象位于该视图模型中。我大致遵循了这个教程:link
  • ChangePageCommand 是 NewCardViewModel 中的一个属性,但可以由 MainViewModel 设置,因此可以在 MainViewModel 中执行一个方法。

标签: c# wpf mvvm data-binding


【解决方案1】:

正如 Clemens 正确建议的那样,最好的解决方案是将 ChangePageCommand 命令留在 NewCardViewModel 级别。创建 NewCardViewModel 时,初始化 ChangePageCommand 命令,使其调用 MainViewModel 中的方法:

public class MainViewModel {
    public void CreateNewCard() {
        NewCardViewModel newCardModel = new NewCardViewModel();
        newCardModel.ChangePageCommand = new RelyCommand(Cancel);
        //...
    }
    void Cancel() {

    }
}

public class NewCardViewModel {
    public ICommand ChangePageCommand {
        get;
        set;
    }
}

在这种情况下,下面的简单绑定应该可以正常工作:

<Button Command="{Binding ChangePageCommand}" ... />

如果您不希望以这种方式在 MainViewModel 中初始化 NewCardViewModel,您可以使用 free DevExpress MVVM Framework 来制作子视图模型 aware of their parents。

另一个可用于相同 MVVM 框架的解决方案是使用Messenger 在不同的视图模型之间进行通信。使用这种方法,您可以在 MainViewModel 级别注册一个操作并从 NewCardViewModel 调用它,而无需创建任何强依赖关系甚至接口。

【讨论】:

  • 这能够完成我所需要的,非常感谢。我有更好的理解。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 1970-01-01
  • 2020-08-01
相关资源
最近更新 更多