C# 文本绑定到本地属性:验证无效
我是WPF的新手,有一个(在我看来)奇怪的问题: 我想将本地属性(名称:XmlText)绑定到TextBox.Text属性,并使用如下验证规则验证该值:C# 文本绑定到本地属性:验证无效,c#,wpf,validation,binding,C#,Wpf,Validation,Binding,我是WPF的新手,有一个(在我看来)奇怪的问题: 我想将本地属性(名称:XmlText)绑定到TextBox.Text属性,并使用如下验证规则验证该值: <TextBox Height="23" Width="301" Margin="78,14,0,0" Name="tbXMLFile" HorizontalAlignment="Left" VerticalAlignment="Top" TextChanged="tbXMLFile_TextChanged"> <Te
<TextBox Height="23" Width="301" Margin="78,14,0,0" Name="tbXMLFile" HorizontalAlignment="Left" VerticalAlignment="Top" TextChanged="tbXMLFile_TextChanged">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors),
Converter={StaticResource ErrorsToStringConverter}}"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
<TextBox.Text>
<Binding Path="XmlText" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:RegexValidationRule Dateiendung="xml"></local:RegexValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
有人能解释一下为什么程序会这样做吗?真正的问题是验证规则:它们不是为实现您的想法而设计的! 请参阅本文,以获取更多详细信息: (使用WPF数据绑定模型时,可以将ValidationRules与绑定对象关联。若要创建自定义规则,请创建此类的子类并实现Validate方法。或者,可以使用内置的ExceptionValidationRule(捕捉源更新期间引发的异常),也可以使用DataErrorValidationRule(捕获源更新期间引发的异常)检查源对象的IDataErrorInfo实现引发的错误。 绑定引擎每次将输入值(即绑定目标属性值)传输到绑定源属性时,都会检查与绑定关联的每个ValidationRule。) 如果在对象绑定的类中实现
System.ComponentModel.IDataErrorInfo
接口,则将捕获任何验证(分配绑定属性以及从UI)
它们只是两种方法,我将向您展示一个具有属性的示例:
public class TestObject : INotifyPropertyChanged, IDataErrorInfo
{
private string _xmlText;
public string XmlText
{
get
{
return _xmlText;
}
set
{
if (value != _xmlText)
{
_xmlText = value;
NotifyPropertyChanged("XmlText");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
handler(this, new PropertyChangedEventArgs(propertyName));
}
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "XmlText")
{
if (XmlText.Length > 5)
result = "Too much long!";
}
return result;
}
}
}
现在,绑定验证应该可以完美地工作:
<TextBox.Text>
<Binding Path="XmlText"
UpdateSourceTrigger="PropertyChanged"
ValidatesOnDataErrors="True"
Mode="TwoWay" />
</Binding>
</TextBox.Text>
您是否为要设置为DataContext的对象类实现了INotifyPropertyChanged?在属性XmlText中,当值更改时,您应该引发PropertyChanged事件…感谢您的帮助:)问题是,我忘记设置绑定模式=“双向”…在一切正常工作之后,即使没有TextChanged事件^^,也可以将其标记为已解决:)非常好:)…它是否也适用于ValidationRule?还是和IDataErrorInfo一起?
<TextBox.Text>
<Binding Path="XmlText"
UpdateSourceTrigger="PropertyChanged"
ValidatesOnDataErrors="True"
Mode="TwoWay" />
</Binding>
</TextBox.Text>