如何通过MVVM模式使用命令正确实现TextChanged事件

3
我正在学习使用MVVM模式的WPF。我的应用程序正在计算身体质量指数,因此非常简单 - 只是为了帮助我理解这种模式的基础知识。
我进行了一些实验,并决定通过命令实现TextChanged事件,以允许用户在输入身高或体重时查看整体BMI标签中的更改。
我在使用TextChanged命令的textBoxes中将其绑定到ViewModel属性时使用了TwoWay模式,因此我认为如果当TextChanged事件发生时在绑定到这些textBoxes的属性上引发INotifyPropertyChanged事件,它将自动更新View,但它并没有。
所以问题是,我做错了什么,如何正确实现它?
PS.除了View更新之外,其他所有内容都有效(已使用命令,我使用断点检查,只是不会更改View)
提前感谢
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>


2
只需在文本框绑定的属性的属性设置器中完成。您可以省略TwoWay标志,因为该属性的默认值为“双向绑定”,但应添加UpdateSourceTrigger=PropertyChanged以便每次用户键入字符时都会更新该属性。 - 15ee8f99-57ff-4f92-890c-b56153
非常感谢,它完全按照我想要的方式工作 :) 对于有类似问题的任何人,我将写一个答案。 - pablocity
1个回答

8
Ed Plunkett 提供了最简单的解决方案:
不需要编写大量代码来实现在 TextChanged 发生时执行命令,有一个名为 UpdateSourceTrigger 的绑定属性可以确定何时进行更新,默认情况下它被设置为 LostFocus,例如当你点击另一个控件时,如果你想在用户输入时更新它,你需要将值设置为 PropertyChanged,就这样!
<TextBox Text="{Binding Person.Weight, UpdateSourceTrigger=PropertyChanged}">

1
哦,我的天啊,我已经寻找了好几个星期了。你太棒了!谢谢你! - Craig

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接