c# - Databind 无法通过 IBindableComponent 进行转换

标签 c# .net winforms

我使用的是 VS2017 IDE,以及 DotNet4.5.2 和 WinForm 框架。

我想用进度条显示一个值,所以我写了下面的代码,它起作用了:

progressBar1.DataBindings.Add(nameof(ProgressBar.Maximum), source, nameof(source.Maximum));
progressBar1.DataBindings.Add(nameof(ProgressBar.Minimum), source, nameof(source.Minimum));
progressBar1.DataBindings.Add(nameof(ProgressBar.Value), source, nameof(source.Status)).Format += (sender,e) => {
    e.Value = (int)(e.Value as IStatus).Value;
};

我想用ToolStripProgressBar来显示它,但是因为它不能进行数据绑定(bind),所以我定义了一个新的类来继承它并实现IBindableComponent如下:

public class BindableToolStripProgressBar : ToolStripProgressBar, IBindableComponent
{
    private BindingContext bindingContext;
    private ControlBindingsCollection dataBindings;

    public BindingContext BindingContext
    {
        get
        {
            if (bindingContext == null)
            {
                bindingContext = new BindingContext();
            }
            return bindingContext;
        }
        set
        {
            bindingContext = value;
        }
    }

    public ControlBindingsCollection DataBindings
    {
        get
        {
            if (dataBindings == null)
            {
                dataBindings = new ControlBindingsCollection(this);
            }
            return dataBindings;
        }
    }
}

然后我将数据绑定(bind)对象从 ProgressBar 更改为新定义的 BindableToolStripProgressBar,但这次运行应用程序导致抛出 System.FormatException:

tspb.DataBindings.Add(nameof(ProgressBar.Maximum), source, nameof(source.Maximum));
tspb.DataBindings.Add(nameof(ProgressBar.Minimum), source, nameof(source.Minimum));
tspb.DataBindings.Add(nameof(ProgressBar.Value), source, nameof(source.Status)).Format += (sender, e) => {
    e.Value = (int)(e.Value as IStatus).Value; // Will be thrown FormatException
};

我对 IBindableComponent 的实现有什么问题吗? 提前致谢!

最佳答案

ToolStripProgressBar 有一个 ProgessBar该属性公开了 ToolStripControlHost 中托管的 ProgressBar 控件。 ToolStripProgressBarMaximumMinimumValue 属性基本上获取或设置底层 ProgressBar 的相应属性

因此您可以设置数据绑定(bind)到底层 ProgressBar:

Source source = new Source() { Minimum = 0, Maximum = 100, Value = 50 };
private void Form1_Load(object sender, EventArgs e)
{
    var p = toolStripProgressBar1.ProgressBar;
    p.DataBindings.Add(nameof(p.Maximum), source, nameof(source.Maximum));
    p.DataBindings.Add(nameof(p.Minimum), source, nameof(source.Minimum));
    p.DataBindings.Add(nameof(p.Value), source, nameof(source.Value));
}

关于c# - Databind 无法通过 IBindableComponent 进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49852774/

相关文章:

.net - 找不到 Azure DevOps NuGet 包

c# - 如何在Winforms RichTextBox中实现基本的语法高亮?

c#应用程序在主窗体关闭时退出

c# - 生成序列A到Z然后0到9,从A到999

c# - 在表单 View 中的转发器中从代码隐藏设置下拉列表上的选定值

c# - 旋转曲线(一系列数据点)X 度定义了新的基线

c# - KeyDown 和 KeyUp 倍数

.net - 使用 .NET 远程更改 Windows 用户密码

c# - 移除动态控制

c# - 如何在 toolstripbutton 上使用工具提示