1

有没有人成功应用 INotifyDataErrorInfo 接口并绑定到 AutoCompleteBox。我已经尝试过了,但我没有得到任何回应。该控件不响应其他控件,即带有红色边框和警告工具提示。它也不会使 Validation Summary 控件显示错误。

我已经成功地设置了标准的 TextBoxes 和 DatePickers,它们的行为完全符合互联网上人们提供的许多示例。

如果为了我的屏幕的一致性有一个答案会很好,也因为我想简单地绑定到 INotifyDataErrorInfo 附带的 HasErrors 属性以在准备保存时启用一个按钮,我不能这样做没有额外的代码来检查这些框是否正确。

目前,我通过使用 MVVMLight EventToCommand 绑定和注册 LostFocus 事件来区别对待这些。

<sdk:AutoCompleteBox x:Name="TransferTypeTextBox" SelectedItem="{Binding Path=SelectedTransferType, Mode=TwoWay, ValidatesOnNotifyDataErrors=True, NotifyOnValidationError=True}" ItemsSource="{Binding Path=TransferTypes}" IsTextCompletionEnabled="True"  Grid.Row="1" Grid.Column="1" Margin="0,3" Width="238" HorizontalAlignment="Left" FontFamily="/PtrInput_Silverlight;component/Fonts/Fonts.zip#Calibri" FontSize="13.333">
      <i:Interaction.Triggers>
           <i:EventTrigger EventName="LostFocus">
               <cmd:EventToCommand Command="{Binding TransferTypeLostFocusCommand}" PassEventArgsToCommand="True"/>
           </i:EventTrigger>
      </i:Interaction.Triggers>
</sdk:AutoCompleteBox>

然后在 ViewModel 中,我将 RoutedEventArgs.OriginalSource 转换为 TextBox 并像这样获取文本,防止用户离开框,除非它为空或匹配框列表中的项目:-

    private void OnTransferTypeLostFocus(RoutedEventArgs e)
    {
        System.Windows.Controls.TextBox box = (System.Windows.Controls.TextBox)e.OriginalSource;

        // If user inputs text but doesn't select one item, show message.
        if (this.Ptr.TransferType == null && !string.IsNullOrEmpty(box.Text))
        {
            MessageBox.Show("That is not a valid entry for Transfer Type", "Transfer type", MessageBoxButton.OK);
            box.Focus();
        }
    }
4

1 回答 1

1

我试着写尽可能简单的例子。我的模型观察属性 SearchText 的变化并更新验证属性。

public class MainViewModel : INotifyPropertyChanged, INotifyDataErrorInfo
{
    private Dictionary<string, List<string>> ErrorMessages = new Dictionary<string, List<string>>();

    public MainViewModel()
    {
        //Validation works automatically for all properties that notify about the changes
        this.PropertyChanged += new PropertyChangedEventHandler(ValidateChangedProperty); 
    }

    //Validate and call 'OnErrorChanged' for reflecting the changes in UI
    private void ValidateChangedProperty(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "HasErrors") //avoid recursion
            return;

        this.ValidateProperty(e.PropertyName);
        OnErrorsChanged(e.PropertyName);
        OnPropertyChanged("HasErrors");
    }

    //Just compare a received value with a correct value, it's a simple rule for demonstration
    public void ValidateProperty(string propertyName)
    {
        if (propertyName == "SearchText")
        {
            this.ErrorMessages.Remove(propertyName);
            if (SearchText != "Correct value")
                this.ErrorMessages.Add("SearchText", new List<string> { "Enter a correct value" });
        }

    }

    private string searchText;

    public string SearchText
    {
        get { return searchText; }
        set
        {
            searchText = value;
            OnPropertyChanged("SearchText");
        }
    }



    #region INotifyDataErrorInfo

    public IEnumerable GetErrors(string propertyName)
    {
        return this.ErrorMessages.Where(er => er.Key == propertyName).SelectMany(er => er.Value);
    }

    public bool HasErrors
    {
        get { return this.ErrorMessages.Count > 0; }
    }

    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged = delegate { };

    private void OnErrorsChanged(string propertyName)
    {
        ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
    }
    #endregion


    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    protected virtual void OnPropertyChanged(string propertyName)
    {
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

和 xaml:

<sdk:AutoCompleteBox Text="{Binding SearchText, Mode=TwoWay}" />
<Button IsEnabled="{Binding HasErrors, Converter={StaticResource NotConverter}}" Content="Save"/>

该控件有一个红色边框,并且当模型出现错误时该按钮被禁用。

于 2011-01-27T22:24:03.903 回答