使用数据绑定在表单上交换UserControls

是否可以在WinForms中使用数据绑定交换两个UserControl?

我想更改应用程序UI依赖于当前选择的ComboBox项目。 我已将我的ComboBox.SelectedValue绑定到属性,并希望现在在该属性的setter中交换UserControls。

我尝试在表单中添加一个大小相同的面板,并尝试将面板DataSource设置为BindingList或类似的东西,不幸的是面板似乎没有类似于ComboBoxDataSource

我很高兴,如果你能给我一个关于如何将我的UserControls数据绑定到我的表单的小提示。 提前致谢。

有点难,但可行。 WF数据绑定的主要问题是缺乏对绑定表达式的支持。 但是,只要source属性提供了更改通知,就可以通过在Binding.Format方法的帮助下使用Binding.Format事件来解决它:

 static void Bind(Control target, string targetProperty, object source, string sourceProperty, Func expression) { var binding = new Binding(targetProperty, source, sourceProperty, true, DataSourceUpdateMode.Never); binding.Format += (sender, e) => e.Value = expression(e.Value); target.DataBindings.Add(binding); } 

与您的案例类似的示例用法:

 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 expression) { var binding = new Binding(targetProperty, source, sourceProperty, true, DataSourceUpdateMode.Never); binding.Format += (sender, e) => e.Value = expression(e.Value); target.DataBindings.Add(binding); } } }