如何通过MVVM命令

时间:2017-06-22 22:13:53

标签: c# wpf mvvm icommand

我正在使用MVVM模式学习WPF。我的应用程序正在计算体重指数,所以它非常简单 - 只是为了帮助我理解这种模式的基础。

我正在尝试一点,并决定通过命令实现TextChanged事件,以允许用户在输入身高或体重时查看整体BMI标签的变化。

我使用TextChanged命令的文本框在TwoWay模式下绑定到ViewModel属性,所以我认为如果我在TextChanged事件发生时绑定到这些textBoxes的属性上引发INotifyPropertyChanged事件,它将自动更新View,但它没有&# 39;吨

所以问题是,我做错了什么以及如何正确实施?

PS。除了查看更新之外的所有其他内容都正常工作(使用命令,我使用断点检查它只是没有更改视图)

提前致谢

CustomCommand类:

public class CustomCommand : ICommand
{

    Action<object> action;
    Predicate<object> predicate;

    public CustomCommand(Action<object> execute, Predicate<object> canExecute)
    {
        action = execute;
        predicate = canExecute;
    }

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

    public bool CanExecute(object parameter)
    {
        if (predicate(parameter))
            return true;
        else
            return false;
    }

    public void Execute(object parameter)
    {
        action(parameter);
    }
}

两个文本框之一:

<TextBox HorizontalAlignment="Left" Height="23" Margin="148,83,0,0" TextWrapping="Wrap" Text="{Binding Person.Weight, Mode=TwoWay}" VerticalAlignment="Top" Width="76">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="TextChanged">
                <i:InvokeCommandAction Command="{Binding Path=textChangedCommand}"></i:InvokeCommandAction>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>

ViewModel,TextChanged方法传递给命令

public class MainWindowViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler propertyChanged = PropertyChanged;

        if (propertyChanged != null)
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }


    public ICommand textChangedCommand { get; set; }

    //public List<float> BMI_Changed;

    private PersonInfo person;


    public PersonInfo Person
    {
        get
        {
            return person;
        }
        set
        {
            person = value;
            OnPropertyChanged("Person");
        }
    }

    public MainWindowViewModel()
    {
        //BMI_Changed = new List<float>();
        textChangedCommand = new CustomCommand(TextChanged, CanBeChanged);
        person = Data.personInfo;
    }


    private void TextChanged(object obj)
    {
        OnPropertyChanged("BMI");
        OnPropertyChanged("Weight");
        OnPropertyChanged("Height");
    }

    private bool CanBeChanged(object obj)
    {
        return true;
    }
}

我的其余视图代码,总体概述:

<Window x:Class="SportCalculators_MVVM.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SportCalculators_MVVM"
    xmlns:enum="clr-namespace:SportCalculators_MVVM.Model"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    mc:Ignorable="d"
    Title="MainWindow" Height="340.278" Width="260.256" Loaded="Window_Loaded"
    DataContext="{Binding Source={StaticResource viewModelLocator}, Path=mainWindowViewModel}">

<Grid x:Name="grid">


    <Slider x:Name="mass" HorizontalAlignment="Right" Margin="0,128,58,0" VerticalAlignment="Top" Width="155" Value="{Binding Person.Weight, Mode=TwoWay}" Maximum="150" Minimum="20"/>
    <Slider x:Name="height" HorizontalAlignment="Left" Margin="40,210,0,0" VerticalAlignment="Top" Width="155" Minimum="100" Maximum="230" Value="{Binding Person.Height, Mode=TwoWay}"/>
    <RadioButton x:Name="sex" Content="Kobieta" HorizontalAlignment="Left" Margin="45,41,0,0" VerticalAlignment="Top" IsChecked="{Binding Person.Sex, Converter={StaticResource ResourceKey=genderConverter}, ConverterParameter={x:Static enum:Sex.Female}}"/>
    <RadioButton x:Name="sex1" Content="Mężczyzna" HorizontalAlignment="Left" Margin="150,41,0,0" VerticalAlignment="Top" IsChecked="{Binding Person.Sex, Converter={StaticResource ResourceKey=genderConverter}, ConverterParameter={x:Static enum:Sex.Male}}"/>
    <Label x:Name="massLabel" Content="Waga" HorizontalAlignment="Left" Margin="40,80,0,0" VerticalAlignment="Top"/>
    <Label x:Name="heightLabel" Content="Wzrost" HorizontalAlignment="Left" Margin="39,167,0,0" VerticalAlignment="Top"/>
    <Label x:Name="label" Content="{Binding Person.BMI}" HorizontalAlignment="Left" Margin="39,274,0,0" VerticalAlignment="Top"/>
    <Button Content="Statystyki" HorizontalAlignment="Left" Margin="149,274,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.325,-0.438"/>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="148,83,0,0" TextWrapping="Wrap" Text="{Binding Person.Weight, Mode=TwoWay}" VerticalAlignment="Top" Width="76">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="TextChanged">
                <i:InvokeCommandAction Command="{Binding Path=textChangedCommand}"></i:InvokeCommandAction>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>

    <TextBox HorizontalAlignment="Left" Height="23" Margin="148,170,0,0" TextWrapping="Wrap" Text="{Binding Person.Height, Mode=TwoWay}" VerticalAlignment="Top" Width="76">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="TextChanged">
                <i:InvokeCommandAction Command="{Binding Path=textChangedCommand}"></i:InvokeCommandAction>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>



</Grid>

1 个答案:

答案 0 :(得分:3)

Ed Plunkett 提供了最简单的解决方案:

在TextChanged发生时,没有必要编写一大堆代码来实现命令,有一个Binding属性 UpdateSourceTrigger 确定何时应该有更新,默认情况下它设置为 LostFocus 所以当你点击另一个控件时,如果你想在用户输入时更新它,你需要将值设置为 PropertyChanged 就是这样!

<TextBox Text="{Binding Person.Weight, UpdateSourceTrigger=PropertyChanged}">