この質問はこのソリューションに基づいていますが、ComboBoxを使用してこれを機能させることができません。送信ボタンをクリックすると、コンボボックスに選択されたアイテムがあり、nullではないことを検証したいと思います。私はわざと何にも拘束されていないことに注意してください。方法がわからないからではありません。ただし、バインドせずに検証ルールを使用する方法がないという答えがある場合(具体的には、ComboBoxに、リンクされたソリューションを介してテキストボックスに実行しました)、お知らせください。
これが私がこれまでに持っているものです:
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はそれをemployeeオブジェクトに変換していません。私はそれが私がそれをバインドしているものと関係があると思います:
<Binding RelativeSoruce="{RelativeSource Self}" Path="GetType"....>
助けていただければ幸いです、ありがとう。