在MVVM中实现textbox lostfocus事件

nos*_*ict 2 c# wpf xaml mvvm

我想完成一项简单的任务.需要实现textbox lostfocus,当用户输入数据时,只要一个字段被填充并且他到达下一个字段,它就应该在前一个字段上激活验证功能.另外,我正在使用MVVM模式.

所以我有这门课

public class data : INotifyPropertyChanged
{

    public string name;
    public string Name
    {
        get
        {
            return name;
        }

        set
        {
            name = value;
            OnPropertyChanged("Name");
        }
    }
    public string firstname;
    public string FirstName
    {
        get
        {
            return firstname;
        }

        set
        {
            firstname = value;
            OnPropertyChanged("FirstName");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            // Raise the PropertyChanged event
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

在Viewmodel中我得到了这个

data1 = new data() { name = "Eddie Vedder", firstname = "Eddie" }; //this line in initialization 
public data _data1;
public data data1
{
    get { return _data1; }
    set 
    {

        _data1 = value;
        ValidateThis();
        NotifyPropertyChanged(new PropertyChangedEventArgs("data1"));
    }
}
Run Code Online (Sandbox Code Playgroud)

在Xaml中:

<StackPanel Orientation="Horizontal" >
    <Label Width="90" Content="Name" Height="28" HorizontalAlignment="Left" Name="lblName" VerticalAlignment="Top" />
    <TextBox Text="{Binding Path=data1.name, UpdateSourceTrigger=LostFocus, Mode=TwoWay}"   MaxLength="40" TabIndex="2" Height="25" Margin="0,3,0,0" HorizontalAlignment="Left" Name="txtName" VerticalAlignment="Top" Width="200" />
</StackPanel>
<StackPanel Orientation="Horizontal" >
    <Label Width="90" Content="First Name" Height="28" HorizontalAlignment="Left" Name="lblFirstName" VerticalAlignment="Top" />
    <TextBox Text="{Binding  Path=data1.firstname, UpdateSourceTrigger=LostFocus, Mode=TwoWay}" MaxLength="40" TabIndex="3" Name="txtFirstName" Height="25" Margin="0,3,0,0" VerticalAlignment="Top" Width="200" >
    </TextBox>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

当我执行它时,我的绑定工作正如它默认名称Eddie Vedder.当我调试它时,它不会输入类数据.

Ale*_*aev 13

当你使用MVVM模式时,我假设你有一些绑定来查看模型属性,它看起来像:Xaml:

<StackPanel>
    <!--Pay attention on UpdateSourceTrigger-->
    <TextBox Text="{Binding Text, UpdateSourceTrigger=LostFocus}" />
    <TextBox />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

C#:

private string _text;
public string Text
{
    get { return _text; }
    set
    {
        _text = value;
        Validate(); // Desired validation
        OnPropertyChanged();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果将UpdateSourceTrigger设置为LostFocus,则在失去焦点时将触发属性更改.