2013-02-09 81 views
0

我在Silverlight中有一個自動完成框,它綁定到一個集合。它工作正常。我只是想要它,以便用戶不能輸入任何不在集合中的值。自動完成框驗證

例如:集合包含值「Head」。如果用戶輸入Headx或其他東西,應該激活驗證。

該怎麼辦?

問候

阿倫

+0

你應該檢查每次SelectedItem屬性爲空或不是上的GotFocus您的回覆 – 2013-02-11 05:03:20

回答

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的bug ......更好的方法是在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(); 
    } 
0

你應該只是能夠改變你的綁定來實現這一點。

默認情況下,文本屬性通常在控件失去焦點時更新綁定源。通過設置綁定來更新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

+0

感謝 – user2056776 2013-02-12 11:03:01

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(); 
     } 
} 

問候

普里亞