ErrorProvider-更改BackColor而不显示图标 [英] ErrorProvider - Change BackColor Instead of Showing Icon
问题描述
我遇到了一些我想升级的遗留代码.我想更改ErrorProvider
在控件上显示错误状态的方式.默认行为是图标,如果将鼠标悬停在图标上,则默认值为ToolTip
.
I'm stuck with some legacy code that I want to upgrade a bit. I want to change the way the ErrorProvider
shows the error status on a Control. Default behavior is the Icon, and a ToolTip
if you hover on the icon.
我想将此行为更改为与我们在WPF控件中使用的行为更相似.这是红色的底色(鲑鱼粉)和控件本身的工具提示.
I would like to change this behavior to be more similar to what we use in our WPF controls. Which is a red back-color(Salmon pink) and the tool-tip on the control itself.
任何提示,链接或前进的方式
Any tips, links or some way forward
编辑. 有关我最终得到的结果,请参见下面的答案.
EDIT. See my answer below, on what i ended up with.
推荐答案
ErrorProvider
组件不支持此功能,如果需要,可以自己创建.
ErrorProvider
component doesn't support this feature and if you need it you can create it yourself.
您可以订阅BindingManagerBase
的BindingComplete
事件,然后可以使用类型为BindingCompleteEventArgs
的事件arg,该事件包含一些有用的属性:
You can subscribe to BindingComplete
event of a BindingManagerBase
and then you can use the event arg which is of type BindingCompleteEventArgs
that contains some useful properties:
-
ErrorText
确定数据绑定中是否存在错误 -
Binding.Control
确定绑定到的控件
ErrorText
to determine if there is an error in data-bindingBinding.Control
to determine the control which is bounded to
这些足以让我们实施我们的解决方案.
These are enough for us to implement our solution.
代码
这是一个示例代码,它显示如何处理BindingComplete
事件并根据其有效或无效状态使用它来更改BackColor
和控件的工具提示.
Here is a sample code which shows how can you handle BindingComplete
event and use it to change BackColor
and tool-tip of a control based on it's valid or invalid state.
假设您有一个绑定源myBindingSource
,该源已绑定到实现为IDataErrorInfo
的SampleModel
类.您可以订阅this.BindingContext[this.myBindingSource]
的BindingComplete
事件:
Suppose you have a binding source, myBindingSource
which is bound to a SampleModel
class which is implemented IDataErrorInfo
. You can subscribe to BindingComplete
event of this.BindingContext[this.myBindingSource]
:
private void Form1_Load(object sender, EventArgs e)
{
this.myBindingSource.DataSource = new SampleModel();
var bindingManager = this.BindingContext[this.myBindingSource];
bindingManager.BindingComplete += bindingManager_BindingComplete;
}
Dictionary<Control, Color> Items = new Dictionary<Control, Color>();
private void bindingManager_BindingComplete(object sender, BindingCompleteEventArgs e)
{
var control = e.Binding.Control;
//Store Original BackColor
if (!Items.ContainsKey(control))
Items[control] = control.BackColor;
//Check If there is an error
if (!string.IsNullOrEmpty(e.ErrorText))
{
control.BackColor = Color.Salmon;
this.errorToolTip.SetToolTip(control, e.ErrorText);
}
else
{
e.Binding.Control.BackColor = Items[e.Binding.Control];
this.errorToolTip.SetToolTip(control, null);
}
}
这篇关于ErrorProvider-更改BackColor而不显示图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!