簡體   English   中英

WPF / Caliburn.Micro-使用IDataErrorInfo進行輸入驗證

[英]WPF/Caliburn.Micro - Input Validation using IDataErrorInfo

我的WPF應用程序中包含以下代碼,並且正在嘗試實現輸入驗證。

模型:

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

ViewModel:

public class CustomerViewModel : Screen, IDataErrorInfo
{
    private Customer _customer;
    public Customer Customer
    {
        get { return _customer; }
        set
        {
            if (_customer != value)
            {
                _customer = value;
                NotifyOfPropertyChange(() => Customer);
            }
        }
    }

    public string Error
    {
        get
        {
            throw new NotImplementedException();
        }
    }

    public string this[string columnName]
    {
        get
        {
            string result = null;
            if (columnName == "Name")
            {
                if (string.IsNullOrEmpty(Customer.Name))
                    result = "Please enter a Name";
                if (Customer.Name.Length < 3)
                    result = "Name is too short";
            }
            return result;
        }
    }
}

視圖:

<TextBox Text="{Binding Customer.Name, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=true, NotifyOnValidationError=true}"/>

問題:解決方案無法按預期工作。 在文本框中鍵入數據時,什么也沒有發生。 我不確定天氣是否遵循正確的步驟。

有人可以幫我嗎?

我認為出現此問題是因為視圖模型中沒有Name屬性(但在Customer類內部)。 在綁定的Customer.Name使用嵌套屬性的工作。

我還沒有將此與IDataErrorInfo驗證結合使用。

當前,您在查看模型索引器中的這種情況將不會得到滿足:

if (columnName == "Name")
{
...
}

因為從未調用過索引器。


我的建議

Name屬性添加到您的視圖模型中,該屬性將代表客戶名稱。 然后,您可以使用諸如set之類的客戶類來初始化視圖模型

Name = customer.Name

在視圖模型構造函數中。

您的綁定將需要更改為

<TextBox Text="{Binding Name  ....

完成此操作后,索引器應該可以工作了,因為現在視圖模型中有了Name屬性。

也許還有另一種解決方案可以讓您保持當前的嵌套綁定( Customer.Name ),但我不確定這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM