AutocompleteBox验证

时间:2013-02-09 09:25:04

标签: c# silverlight

我在silverlight中有一个自动完成框,它绑定到一个集合。它工作正常。我只是想要它,以便用户不能输入任何不在集合中的值。

例如:Collection包含值“Head”。如果用户输入Headx或其他内容,则应触发验证。

怎么做?

此致

阿伦

3 个答案:

答案 0 :(得分:1)

试试这个

<Sdk:AutoCompleteBox Grid.Column="3" Grid.Row="3" Height="18" Width="150" 
     IsTextCompletionEnabled="True" TabIndex="9" HorizontalAlignment="Left"

     Text="{Binding ElementName=ResEdit,Path=DataContext.SelectedDemoText,Mode=TwoWay}"
     ItemsSource="{Binding ElementName=ResEdit,Path=DataContext.DemoList,Mode=OneWay}"
     ItemTemplate="{StaticResource DemoTemplate}"
     ValueMemberPath="DemoCode" 
     LostFocus="AutoCompleteBox_LostFocus"
     Margin="0,0,21,0" Padding="0">
  </Sdk:AutoCompleteBox>

您不应在自动完成中同时使用函数SelectedText和SelectedItem。这是AutoCompleteBox的一个错误.....更好的方法是在GotFocus和LossFocus上设置文本框和AutoCompleteBox的可见性。这种方式你会直截了当地解决你的问题

 private void DemoAutoComplete_LostFocus(object sender, RoutedEventArgs e)
            {
                DemoTextBox.Visibility = Visibility.Visible;
                DemoAutoComplete.Visibility = Visibility.Collapsed;
                DemoTextBox.Text = OCRAutoComplete.Text;

                ((DemoVM)this.DataContext).SelectedDemoText = DemoAutoComplete.Text;
            }



private void DemoTextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        DemoAutoComplete.Text = OctTextBox.Text;
        DemoTextBox.Visibility = Visibility.Collapsed;
        DemoAutoComplete.Visibility = Visibility.Visible;
        DemoAutoComplete.Focus();
    }

答案 1 :(得分:0)

您应该能够更改Binding以实现此目的。

默认情况下,文本属性通常在控件失去焦点时更新绑定源。通过将Binding设置为更新PropertyChanged上的源,您可以通过每次击键实现验证。

您在Text属性上的绑定看起来像这样

Text="{Binding MyProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

在您的属性设置器中,您可以在认为合适时抛出ValidationException,或者您可以实现其中一个验证接口(INotifyDataErrorInfoIDataErrorInfo)并处理它方式。

This article is a good source of info about the complexities of data Binding

答案 2 :(得分:0)

我最近在研究过这个问题。我的问题通过检查解决了 自动填充框丢失焦点事件的选定项属性。

private void autoCompleteBox1_LostFocus(object sender, RoutedEventArgs e)     
{     
     if (autoCompleteBox1.SelectedItem == null && !string.IsNullOrEmpty(autoCompleteBox1.Text))
      {
       MessageBox.Show("Please fill in the right value");
       autoCompleteBox1.Text = "";
       autoCompleteBox1.Focus();
        }
}

此致

普里亚