用表格的Exchange用户控件数据绑定 [英] Exchange UserControls on a Form with data-binding
问题描述
是否有可能在的WinForms交换两个用户控件与数据绑定?
Is it possible to exchange two UserControls with databinding in WinForms?
我想改变目前选定ComboBox项应用程序UI dependending。我已绑定我的 ComboBox.SelectedValue
来的属性,并希望该属性的setter方法中,现在交换用户控件。
I would like to change the applications UI dependending on which ComboBox item is currently selected. I have bound my ComboBox.SelectedValue
to a property and would like to exchange the UserControls now within the setter of that property.
我尝试添加一个同样大小的面板的形式,并试图面板数据源
设置为的BindingList<控制>
或类似的东西,可惜面板似乎并不有一个数据源
类似于组合框
...
I tried adding a equally sized panel to the form and tried setting the panels DataSource
to a BindingList<Control>
or something similar, unfortunately a panel doesn't seem to have a DataSource
similar to a ComboBox
...
我会很高兴,如果你能给我如何进行数据绑定用户控件我对我形成一个小提示。先谢谢了。
I would be glad, if you could give me a small hint on how to databind my UserControls to my form. Thanks in advance.
推荐答案
一个有点困难,但可行的。 WF中的数据绑定的主要问题是缺乏对绑定表达式的支持。
A little bit harder, but doable. The main problem in WF data binding is the lack of support for binding expressions. However, as soon as the source property provides change notification, it can be solved by using the Binding.Format
event with the help of a methods like this:
static void Bind(Control target, string targetProperty, object source, string sourceProperty, Func<object, object> expression)
{
var binding = new Binding(targetProperty, source, sourceProperty, true, DataSourceUpdateMode.Never);
binding.Format += (sender, e) => e.Value = expression(e.Value);
target.DataBindings.Add(binding);
}
示例用法类似于你的情况:
Sample usage similar to your case:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Tests
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form = new Form();
var topPanel = new Panel { Dock = DockStyle.Top, Parent = form };
var combo = new ComboBox { Left = 8, Top = 8, Parent = topPanel };
topPanel.Height = combo.Height + 16;
combo.Items.AddRange(new[] { "One", "Two" });
combo.SelectedIndex = 0;
var panel1 = new Panel { Dock = DockStyle.Fill, Parent = form, BackColor = Color.Red };
var panel2 = new Panel { Dock = DockStyle.Fill, Parent = form, BackColor = Color.Green };
Bind(panel1, "Visible", combo, "SelectedIndex", value => (int)value == 0);
Bind(panel2, "Visible", combo, "SelectedIndex", value => (int)value == 1);
Application.Run(form);
}
static void Bind(Control target, string targetProperty, object source, string sourceProperty, Func<object, object> expression)
{
var binding = new Binding(targetProperty, source, sourceProperty, true, DataSourceUpdateMode.Never);
binding.Format += (sender, e) => e.Value = expression(e.Value);
target.DataBindings.Add(binding);
}
}
}
这篇关于用表格的Exchange用户控件数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!