我正在尝试验证在WPF中的Datagrid中输入的输入。
我已经向XAML添加了验证规则。
输入是一个对象,只是一个字符串或int。虽然我使用的方法需要一个对象。
如何解决问题并使其与int或字符串一起使用。输入只能是1到20之间的int。
XAML :
<DataGridTextColumn Header="Niveau">
<DataGridTextColumn.Binding>
<Binding Path="Niveau" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<valRule:NiveautredeValidationRule />
</Binding.ValidationRules>
</Binding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
C#
public class NiveautredeValidationRule : ValidationRule
{
public override System.Windows.Controls.ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
NiveaudoelenViewModel doel = (value as BindingGroup).Items[0] as NiveaudoelenViewModel;
if (doel.Niveau <= 0 || doel.Niveau > 20)
{
return new System.Windows.Controls.ValidationResult(false, "Niveau moet tussen de 1 en 20 zijn!");
}
else
{
return System.Windows.Controls.ValidationResult.ValidResult;
}
}
}
答案 0 :(得分:1)
你可以试试这个:
public override System.Windows.Controls.ValidationResult Validate(object value,
System.Globalization.CultureInfo cultureInfo)
{
int myInt = 0;
try
{
if (((string)value).Length > 0)
myInt = int.Parse((String)value);
}
catch (Exception e)
{
return new ValidationResult(false, "Illegal characters or " + e.Message);
}
if (myInt < 0 || myInt > 20)
{
return new ValidationResult(false,
"Please enter a number in the range: 0 - 20");
}
else
{
return new ValidationResult(true, null);
}
}
来源:https://docs.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-implement-binding-validation
答案 1 :(得分:1)
你应该考虑更新这个的受理答案,
这消除了foreach (System.Windows.Forms.Control e in this.Controls)
{
ElementHost c= e as ElementHost;
if ( c != null )
{
TP1WPFControls.TP1CustomButton bt = c.Child as TP1CustomButton;
if ( bt != null )
{
// Add Events (I'd assume it would just be bt.MouseEnter but I don't know what your control looks like)
bt.bt.MouseEnter += Bt_MouseEnter;
bt.bt.MouseLeave += Bt_MouseLeave;
}
}
}
并使用TryParse代替
try catch