0
這個問題是基於this solution,但我不知何故無法使用ComboBox得到這個工作。我想驗證一下,點擊一個提交按鈕後,組合框有一個選定的項目,而不是空的。請注意,我不是故意要約的,也不是因爲我不知道如何去做。但是,如果答案是我無法使用驗證規則而沒有綁定(特別是ComboBoxes,我已經通過鏈接解決方案將其添加到了文本框中),請讓我知道。無綁定組合框驗證
這是我到目前爲止有:
XAML:
<ComboBox DataContext="{StaticResource ChargeAssigneeViewSource}" Name="ChargeAssigneeBox" ItemsSource="{Binding}" Width="85">
<ComboBox.SelectedItem>
<Binding RelativeSource="{RelativeSource Self}" Path="GetType" Mode="TwoWay">
<Binding.ValidationRules>
<my:ComboBoxValidationRule ErrorMessage="Please select an Assignee" />
</Binding.ValidationRules>
</Binding>
</ComboBox.SelectedItem>
</ComboBox>
驗證規則:
class ComboBoxValidationRule : ValidationRule
{
private string errorMessage;
public string ErrorMessage
{
get { return errorMessage; }
set { errorMessage = value; }
}
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value == null)
return new ValidationResult(false, ErrorMessage);
return new ValidationResult(true, null);
}
}
按鈕點擊:
private void AddAnHours()
{
Employee currEmployee;
if (!ValidateElement.HasError(ChargeAssigneeBox))
{
if (!ValidateElement.HasError(analystTimeTxtBox))
{
currEmployee = ChargeAssigneeBox.SelectedItem as Employee;
item.AddTime(currEmployee, DateTime.Now, double.Parse(analystTimeTxtBox.Text));
analystTimeTxtBox.Clear();
ChargeAssigneeBox.SelectedItem = null;
}
}
UpdateTotals();
}
,我得到的錯誤在這一行:
currEmployee = ChargeAssigneeBox.SelectedItem as Employee;
但我的ItemsSource綁定正確,所以即使我選擇了一個項目,selecteditem不會將其轉換爲員工對象。我懷疑它與我綁定它有什麼關係:
<Binding RelativeSoruce="{RelativeSource Self}" Path="GetType"....>
幫助將不勝感激,謝謝。
我不想繼續爲每個沒有綁定的組合框項目執行此操作。而且我不想每次都將它綁定到同一個項目上。如果這是不可能的,那就說出來,否則當它包含這種類型的解決方案時,我無法得到答案。 – Erika 2012-07-27 19:50:42