如果存在重复,如何清除/阻止绑定到datagrid?

时间:2014-05-14 03:19:47

标签: c# wpf datagrid

这是我的财产,决定我是否应该绑定其他财产:

public string LotNumber {
        get {
            return lotNumber;
        }
        set {
            using (var db = new DDataContext()) {
                lotNumber = value;
                // Check for duplicates
                bool isDuplicate =
                     db.LotInformation.Any(r => r.lot_number == lotNumber);
                if (isDuplicate == true) {
                    ComponentsList = null;
                    FamiliesList = null;
                    ExpirationDate = null;
                    LotNumber = null;
                    lotNumber = null;
                    // Inform user that the lot_number already exists
                    errorWindow.Message =
                         LanguageResources.Resource.Lot_Exists_Already;
                    dialogService.ShowDialog(
                         LanguageResources.Resource.Error, errorWindow);
                    logger.writeErrLog(
                         LanguageResources.Resource.Lot_Exists_Already);
                    return;
                } else {
                    lotNumber = value;
                }
                RaisePropertyChanged("LotNumber");
            }
        }
    }

我现在的问题是,如果我上传了一个文件,并且如果批号已经存在于数据库中,则布尔值返回true并抛出错误消息。然而,在那之后,它再次循环然后布尔值设置为false,因为现在该值为null并且它仍然在之后绑定数据。如果在上面的情况下bool为真,我该如何突破循环并使其停止运行/清除/阻止绑定?

1 个答案:

答案 0 :(得分:1)

我假设你有这样的代码:

LotNumber = "ABC5";  // ABC5 already exists in the database - uh oh!

然后你试图在“二传手”中找出所有内容。到目前为止已经太晚了。相反,将您的逻辑移到单独的方法中:

private bool LotNumberExists(string lotNumber)
{
    using (var db = new DDataContext())
    {
        return db.LotInformation.Any(r => r.lot_number == lotNumber);
    }
}

private void ClearFields()
{
    ComponentsList = null;
    FamiliesList = null;
    ExpirationDate = null; 
    LotNumber = null;
}

private void InformUserOfDuplicate()
{
    // Inform user that the lot_number already exists
    errorWindow.Message = LanguageResources.Resource.Lot_Exists_Already;
    dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
    logger.writeErrLog(LanguageResources.Resource.Lot_Exists_Already);
}

然后在设置LotNumber之前检查该方法的返回值。

private void SomeOtherMethod()
{
    string someLotNumber = "ABC5";

    if (LotNumberExists(someLotNumber)
    {
        ClearFields();

        InformUserOfDuplicate();

        return;
    }

    LotNumber = someLotNumber;
}

将你的二传手变回一个简单的设定者,而不需要大量的逻辑:

public string LotNumber
{
    get { return lotNumber; }
    set
    {
        lotNumber = value;

        RaisePropertyChanged("LotNumber");
    }
}