gpt4 book ai didi

c# - Winforms 数据绑定(bind) : Can a TypeConverter be used instead of the Format/Parse events?

转载 作者:太空狗 更新时间:2023-10-29 20:35:22 30 4
gpt4 key购买 nike

在 Winforms 表单中,我想在输入字段包含无效值时向用户提供视觉提示。为此,我想将输入字段标签的 ForeColor 属性绑定(bind)到基础模型的( bool 值)IsPropertyValid 属性,以便标签在 IsPropertyValid == false

我目前拥有的是绑定(bind)的 Format 事件的事件处理程序:

Controls["dateOfBirthLabel"].DataBindings["ForeColor"].Format += convertBoolToColor;
// (dateOfBirthLabel.ForeColor is bound to a boolean IsDateOfBirthValid property.)

void convertBoolToColor(object sender, ConvertEventArgs e)
{
e.Value = (bool)e.Value ? Color.Black : Color.Red;
}

如果我想在 WPF 中执行此操作,我想我会指定自定义 value converter (boolColor)直接与 XAML 中的绑定(bind)。 最重要的是,我不必通过名称来引用特定控件。

我想对我的 Winforms 表单做同样的事情。理想情况下,我可以直接在 Forms Designer 中为特定绑定(bind)指定 TypeConverter 对象。这可能吗?

最佳答案

My previous answer (now deleted)不正确:这可以完成,使用自定义 TypeConverter .

首先,需要一个合适的转换器。 (与 XAML 不同,它不实现 IValueConverter,而是派生自 TypeConverter。)例如:

// using System;
// using System.ComponentModel;
// using System.Drawing;
// using System.Globalization;

sealed class BooleanToColorConverter : TypeConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context,
Type destinationType)
{
return destinationType == typeof(Color);
}

public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture,
object value,
Type destinationType)
{
return (bool)value ? Color.Green : Color.Red;
}
}

接下来,(并且与 XAML 数据绑定(bind)不同,)此转换器不应用于绑定(bind)本身;它必须使用 [TypeConverter] attribute 附加到数据源的属性:

// using System.ComponentModel;

partial class DataSource : INotifyPropertyChanged
{
[TypeConverter(typeof(BooleanToColorConverter))] // <-- add this!
public bool IsValid { get { … } set { … } }
}

最后formatting必须在数据绑定(bind)上启用:

// Control control = …;
// DataSource dataSource = …;

control.DataBindings.Add("ForeColor", dataSource, "IsValid", formattingEnabled: true);
// ^^^^^^^^^^^^^^^^^^^^^^^

请注意,此示例仅处理单向(数据源到控件)数据绑定(bind)。对于双向数据绑定(bind),您还必须覆盖 TypeConverter.ConvertFromTypeConverter.CanConvertFrom 方法。

关于c# - Winforms 数据绑定(bind) : Can a TypeConverter be used instead of the Format/Parse events?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3430217/

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