我知道这是一个非常古老的帖子,但多年来我已经多次寻找类似的东西,并且对我最终使用的东西从来没有真正满意过。Mike Park 的回答很棒,不仅因为它有效,还因为它非常简单。
我所做的只是接受 Mike 的回答并将其转换为 Control 扩展。谢谢迈克!
根据您使用它的位置和方式,您可能需要添加对 System.Windows.Forms 的引用和 using System.Windows.Forms 语句。
/// <summary>
/// Creates a DataBinding that allows you to bind to the Unchecked state instead of the normal Checked state.
///
/// Sample usage: In this case, I am enabling a Button when the CheckBox is unchecked.
/// // Defaults to Control Enabled property.
/// // Always bound to the DataSource Checked property.
/// YourButton.DataBindings.Add(YourButton.UncheckedBinding(YourCheckBox));
///
/// var binding = YourButton.UncheckedBinding(YourCheckBox);
/// YourButton.DataBindings.Add(binding);
///
/// Adapted - from answer by Mike Park answered Oct 18 '12 at 19:11
/// From: Databinding Enabled if false
/// Link: https://stackoverflow.com/questions/12961533/databinding-enabled-if-false
/// </summary>
/// <typeparam name="T">Constrained to be a type that inherits from ButtonBase. This includes CheckBoxes and RadionButtons.</typeparam>
/// <param name="control">The control that will consume the DataBinding.</param>
/// <param name="DataSource">The control to which we are binding. We will always bind to the Checked property.</param>
/// <returns>DataBinding that is bound to the Unchecked state instead of the usual Checked state.</returns>
public static Binding UncheckedBinding<T>(this Control control, T DataSource) where T : ButtonBase
{
return UncheckedBinding(control, "Enabled", DataSource);
}
/// <summary>
/// Creates a DataBinding that allows you to bind to the Unchecked state instead of the normal Checked state.
///
/// Sample usage: In this case, I am enabling a Button when the CheckBox is unchecked.
/// // Always bound to the DataSource Checked property.
/// YourButton.DataBindings.Add(YourButton.UncheckedBinding("Enabled", YourCheckBox));
///
/// var binding = YourButton.UncheckedBinding(YourCheckBox);
/// YourButton.DataBindings.Add(binding);
///
/// Adapted - from answer by Mike Park answered Oct 18 '12 at 19:11
/// From: Databinding Enabled if false
/// Link: https://stackoverflow.com/questions/12961533/databinding-enabled-if-false
/// </summary>
/// <typeparam name="T">Constrained to be a type that inherits from ButtonBase. This includes CheckBoxes and RadionButtons.</typeparam>
/// <param name="control">The control that will consume the DataBinding.</param>
/// <param name="DataSource">The control to which we are binding. We will always bind to the Checked property.</param>
/// <param name="PropertyName">The name of the property that is being bound.</param>
/// <returns>DataBinding that is bound to the Unchecked state instead of the usual Checked state.</returns>
public static Binding UncheckedBinding<T>(this Control control, string PropertyName, T DataSource) where T : ButtonBase
{
var binding = new Binding(PropertyName, DataSource, "Checked");
binding.Format += (sender, e) => e.Value = !((bool)e.Value);
return binding;
}