我对ComboBox
上的绑定有问题,我不明白为什么它不起作用:
以下代码绑定对象上的项目,它完美地运行:
<ComboBox Grid.Row="4" Grid.Column="2" Name="comboBoxDefinedBy" Style="{StaticResource ComboBoxStandard}" Margin="0,0,5,0" ItemTemplate="{StaticResource DealerTemplateComboBox}" SelectedValue="{Binding DefinedBy_Id, Mode=TwoWay}" SelectedValuePath="Id">
</ComboBox>
以下不起作用,验证规则完美运行:
<ComboBox Grid.Row="4" Grid.Column="2" Name="comboBoxDefinedBy" Style="{StaticResource ComboBoxStandard}" Margin="0,0,5,0" ItemTemplate="{StaticResource DealerTemplateComboBox}" SelectedValuePath ="DefinedBy_Id">
<ComboBox.SelectedItem>
<Binding Path="Id" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
<Binding.ValidationRules>
<customValidationRules:ComboBoxIsNotEmptyValidationRule></customValidationRules:ComboBoxIsNotEmptyValidationRule>
</Binding.ValidationRules>
</Binding>
</ComboBox.SelectedItem>
</ComboBox>
答案 0 :(得分:1)
正如article所说,你有几个选择。
您可以将SelectedItem
绑定到某个媒体资源,然后对此进行验证
private MyDataObject _someData;
public MyDataObject SomeData
{
get
{
return _ someData;
}
set
{
_ someData = value;
if (value == null || string.IsNullOrEmpty(value.MyProperty))
throw new ApplicationException("SomeData is required");
}
}
<ComboBox.SelectedItem>
<Binding Path="SomeData" ElementName="Window">
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</ComboBox.SelectedItem>
或者,您可以创建自己的验证规则,然后像这样执行
public class MyCustomValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value is MyDataObject)
{
var myDataObj = (MyDataObject)value;
if (myDataObj.CheckCustomBusinessRules())
return new ValidationResult(true, null);
}
return new ValidationResult(false, "Invalid selection!");
}
}
<ComboBox.SelectedItem>
<Binding Path="SomeData" ElementName="Window">
<Binding.ValidationRules>
<local:PersonValidation />
</Binding.ValidationRules>
</Binding>
</ComboBox.SelectedItem>
进一步采取这一步骤,正如question建议的那样,将ValidationRules
替换为IDataErrorInfo
之类的内容。这个article很好地概述了验证的不同方法。