gpt4 book ai didi

c# - Validation.ErrorTemplate 确实在绑定(bind)到对象属性时触发

转载 作者:行者123 更新时间:2023-12-03 10:49:19 25 4
gpt4 key购买 nike

就像这样,我有一个 wpf 绑定(bind)

<TextBox
Name="txtRackNo"
Grid.Column="5"
Grid.ColumnSpan="7"
Grid.Row="4"
Grid.RowSpan="1"
Style="{StaticResource ResourceKey=styleValidationTextBox}"
Text="{Binding Path=rack_no, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}">
</TextBox>

如果我实现 IDataErrorInfo 并直接在我的 View 模型中拥有属性,那么它可以工作,它会显示工具提示和红色验证框。
如果我在作为 View 模型属性的类中实现 IDataErrorInfo,则样式会创建工具提示,但不会显示红色错误框。我确信我的风格是有效的,只是如果我改变这条线
Text="{Binding Path=rack_no, Mode=TwoWay, ...}" 

使用我的数据类型“RACK”
Text="{Binding Path=rack.rack_no, Mode=TwoWay, ...}"

private Rack _rack;
public Rack rack
{
get { return _rack; }
set
{
_rack = value;
createPropertyObserver();
base.RaisePropertyChanged("rack");
}
}

然后它只显示工具提示而不是红色验证错误框。

编辑:这里有更多代码,也许这会帮助别人更好地理解我的问题?
class Rack : ObservableObject, IDataErrorInfo
{
public String _rack_no;
public String rack_no
{
get { return _rack_no; }
set
{
if (value != null)
{
_rack_no = value;
base.RaisePropertyChanged("rack_no");
}
}
}

public String Error
{
get { return this[null]; }
}

public String this[String propertyName]
{
get
{
String result = String.Empty;
propertyName = propertyName ?? String.Empty;
if (propertyName == String.Empty || propertyName == "dc_name")
{
if (String.IsNullOrEmpty(this.dc_name))
{
result += "Datacenter name is mandatory." + Environment.NewLine;
}
}

if (propertyName == String.Empty || propertyName == "rack_no")
{
if (String.IsNullOrEmpty(this.rack_no) || this.rack_no.Length > 5)
{
result += "Rack number is mandatory and must be 5 letters or less."
+ Environment.NewLine;
}
}
Debug.WriteLine(result);
return result.TrimEnd();
}
}

然后这是我的 View 模型的一部分:
              private Rack _rack;
public Rack rack
{
get { return _rack; }
set
{
_rack = value;
createPropertyObserver();
base.RaisePropertyChanged("rack");
}
}

如果在我看来,我将文本框绑定(bind)到 rack.rack_no,如果出现验证错误,则工具提示会起作用并显示正确的错误消息。但是,它不会更改文本框以使用验证样式。

如果我创建相同的属性 (rack_no) 并在我的 View 模型中实现 idataerrorinfo,然后我绑定(bind)到它,它可以完美运行。

我只想知道我是否在这里做错了什么,比如这不是有效的验证绑定(bind)吗?有没有办法让我继续绑定(bind)到 rack.rack_no 类并使用验证?

最佳答案

放弃了这个想法,而是决定使用下面给出的方法:
http://www.codeproject.com/Articles/15239/Validation-in-Windows-Presentation-Foundation

http://www.codeproject.com/Articles/97564/Attributes-based-Validation-in-a-WPF-MVVM-Applicat

这将 idataerrorinfo 与 System.ComponentModel.DataAnnotations 结合使用;执行验证。我还更改了我的验证样式以手动创建红色框,这似乎解决了在验证绑定(bind)到子对象的数据绑定(bind)时使用默认验证样式的问题。

关于c# - Validation.ErrorTemplate 确实在绑定(bind)到对象属性时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11251673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com