简体   繁体   English

在WPF中使用绑定时如何检查数据

[英]How to check data when using binding in WPF

Maybe this is easy, but I didn't find a solution for my problem yet. 也许这很容易,但是我还没有找到解决问题的方法。

When I use binding and a user changes for example the text in a textbox, how can I perform some backround checks like: 当我使用绑定并且用户更改了例如文本框中的文本时,如何执行一些背景检查:

  • Is this name already in my database 这个名字已经在我的数据库中了吗
  • Does the name fit to my allowed character set 名称是否适合我允许的字符集

Without binding this is easy i just call the functions that do the trick. 如果没有绑定,这很容易,我只需调用完成该功能的函数即可。

Example: 例:

<TextBox x:Name="textbox_Name" Height="23" Margin="108,37,20,0" TextWrapping="Wrap" Text="{Binding Name,UpdateSourceTrigger=LostFocus}" VerticalAlignment="Top"/>
  • The datacontext is ObjectXYZ. 数据上下文为ObjectXYZ。
  • ObjectXYZ has a Name and a Description property. ObjectXYZ具有名称和描述属性。
  • I also have a Database with a ObservableCollection of type "ObjectXYZ" called "list" 我也有一个名为“ list”的ObservableCollection类型为“ ObjectXYZ”的数据库

Normaly I woud do something like: if(!Database.isExistingObject(textbox_Name.Text) { ObjectXYZ.Name=textbox_Name.Text; } 通常,我会做类似的事情: if(!Database.isExistingObject(textbox_Name.Text) { ObjectXYZ.Name=textbox_Name.Text; }

With binding the name gets directly changed(Two way binding)...how can I check it before its changed? 通过绑定,名称可以直接更改(双向绑定)...如何在更改之前进行检查?

You can still call your background checks if you call them right after the user has updated the textbox content. 如果您在用户更新文本框内容之后立即调用背景检查,则仍可以调用它们。

private string name;

public string Name 
{
    get
    {
        return name;
    }

    set
    {           
        CheckName(value); // Or whatever are you check functions

        name = value;

        PropertyChanged("Name");
    }
}

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM