使用MVVM Light在两个控件上解开EventToCommand

时间:2013-10-21 08:11:51

标签: c# wpf mvvm mvvm-light

嗨,我对WPF很陌生,我已经开始使用基于 mvvm light 框架的mvvm模式实现一个应用程序。我发现它很棒,但是我在使用两个EventToCommand对应该在一起交互的控件时遇到了问题。我猜我做错了什么......你能帮我找出究竟是什么吗?

我有一个带有两个控件的窗口:一个允许选择名称的组合框和一个显示标题的文本框。名称具有默认标题(对于ViewModel的构造函数中的示例进行硬编码,请参见下文)。因此,当用户选择名称时,文本框应显示默认标题。但是,标题是可编辑的,这意味着用户可以更改标题(只要他不再更改名称)。

在下面的示例中,我使用MVVM模式和MVVM Light框架实现了这一点。 “确定”按钮仅绑定到在OutPut窗口中记录值的命令(以查看ViewModel中的属性值)。

正如您将在源代码注释中看到的那样,问题来自于NameSelectionChanged命令触发带有“过时值”的CaptionTextChanged命令的事实。现在,我通过在NameSelectionChanged中执行RaisePropertyChanged时设置一个忽略CaptionTextChanged中的代码的布尔值来实现一个hacky变通方法(不在下面的代码中),但它实际上并不令人满意。

XAML中的视图

<Window x:Class="TwoControls.MainWindow"
         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:vm="clr-namespace:TwoControls"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras"
        mc:Ignorable="d" 
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <vm:DummyViewModelLocator x:Key="Locator" d:IsDataSource="True" />
    </Window.Resources>
    <Window.DataContext>
        <Binding Path="GetViewModel" Source="{StaticResource Locator}" />
    </Window.DataContext>
    <Grid>
        <ComboBox ItemsSource="{Binding ColumnNames}"  x:Name="NamesComboBox" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <cmd:EventToCommand Command="{Binding NameSelectionChanged}" CommandParameter="{Binding SelectedValue, ElementName=NamesComboBox}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </ComboBox>
        <TextBox Text="{Binding Caption, Mode=TwoWay}" Name="CaptionTextBox"  HorizontalAlignment="Left" Height="23" Margin="0,45,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="TextChanged">
                    <cmd:EventToCommand Command="{Binding CaptionTextChanged}" CommandParameter="{Binding Text, ElementName=CaptionTextBox}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </TextBox>
        <Button Content="Ok" Command="{Binding ClickOk}" HorizontalAlignment="Left" Margin="120,170,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
</Window>

C#中的视图模型

public class MainViewModel : ViewModelBase
        {
            private readonly List<string> _names;
            private readonly string[] _captions;

            public MainViewModel()
            {
                _names = new List<string>(new[]{"TOTO","TATA","TUTU"});
                _captions = new[] {"toto", "tata", "tutu"};
            }

            public string Name { get; set; }

            public string Caption { get; set; }

            public ICommand NameSelectionChanged
            {
                get
                {
                    return new RelayCommand<string>((input) =>
                        {
                            Name = input;
                            int index = _names.IndexOf(input);
                            Caption = _captions[index];

                            //Trigger the execution of CaptionTextChanged with the old value of the TextBox
                            //even if Caption and TextBox.Text are bound TwoWay....
                            base.RaisePropertyChanged(()=>this.Caption);
                        });
                }
            }

            public ICommand CaptionTextChanged
            {
                get
                {
                    return new RelayCommand<string>((input) =>
                        {
                            Caption = input;
                        });
                }
            }


            public ICommand ClickOk
            {
                get
                {
                    return new RelayCommand(() =>
                    {
                        Console.WriteLine("Name=" + Name +";" +"Caption=" + Caption);
                    });
                }
            }

            public List<string> ColumnNames
            {
                get { return _names; }
            } 
        }

Ps:目标.NET为3.5,MVVMLight版本为4.1.27.1

1 个答案:

答案 0 :(得分:1)

您无需在WPF中使用任何事件来执行此操作。如果您按照惯例在视图模型上实现Binding界面,只需使用属性INotifyPropertyChanged s 就可以实现所有这些......这是怎么回事:

private ObservableCollection<string> columnNames = new 
    ObservableCollection<string>();
public ObservableCollection<string> ColumnNames
{
    get { return columnNames; }
    set { columnNames = value; NotifyPropertyChanged("ColumnNames"); }
}

private string selectedColumnName;
public string SelectedColumnName
{
    get { return selectedColumnName; }
    set 
    { 
        selectedColumnName = value;
        NotifyPropertyChanged("SelectedColumnName");
        int index = _names.IndexOf(value); // <<< Changes are reflected here
        Caption = _captions[index];
    }
}

private string caption = string.Empty;
public string Caption 
{
    get { return caption; }
    set { caption = value; NotifyPropertyChanged("Caption"); }
}

在XAML中:

<Grid>
    <ComboBox ItemsSource="{Binding ColumnNames}" SelectedItem="{Binding 
        SelectedColumnName}" x:Name="NamesComboBox" HorizontalAlignment="Left" 
        VerticalAlignment="Top" Width="120" />
    <TextBox Text="{Binding Caption, Mode=TwoWay}" Name="CaptionTextBox" 
        HorizontalAlignment="Left" Height="23" Margin="0,45,0,0" TextWrapping="Wrap" 
        VerticalAlignment="Top" Width="120" />
    <Button Content="Ok" Command="{Binding ClickOk}" HorizontalAlignment="Left" 
        Margin="120,170,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>

让我知道它是怎么回事。