gpt4 book ai didi

c# - 当我在运行时添加控件时,以编程方式绑定(bind)不起作用

转载 作者:行者123 更新时间:2023-11-30 14:18:59 26 4
gpt4 key购买 nike

我有两个文本框,我想在运行时绑定(bind)它们的 Visibility 属性,

绑定(bind)在我通过 Xaml 添加文本框时有效,但在我以编程方式添加时无效,

任何帮助!!

    public partial class Window1 : Window
{
TextBox txt1 = new TextBox();
TextBox txt2 = new TextBox();
public Window1()
{
InitializeComponent();

txt1.Name = "txt1";
txt1.Margin= new Thickness(30,0,128,0);
txt1.VerticalAlignment = VerticalAlignment.Top;

txt2.Name = "txt2";
txt2.Margin = new Thickness(30, 32, 128, 0);
txt2.VerticalAlignment = VerticalAlignment.Top;

Binding binding = new Binding();
binding.ElementName = "txt1";
binding.Path = new PropertyPath(TextBox.VisibilityProperty);
BindingOperations.SetBinding(txt2, TextBox.VisibilityProperty, binding);


grid.Children.Add(txt1);
grid.Children.Add(txt2);
}
}

提前致谢

最佳答案

已更新

无需设置 ElementName 属性,只需将 BindingSource 属性设置为您希望绑定(bind)到的 Element 对象即可。

TextBox txt1 = new TextBox();
TextBox txt2 = new TextBox();

public Window1()
{
InitializeComponent();

txt1.Name = "txt1";
txt1.Margin = new Thickness(30, 0, 128, 0);
txt1.VerticalAlignment = VerticalAlignment.Top;
txt1.Visibility = Visibility.Visible;

txt2.Name = "txt2";
txt2.Margin = new Thickness(30, 32, 128, 0);
txt2.VerticalAlignment = VerticalAlignment.Top;

Binding binding = new Binding();
binding.Source = txt1; // set the source object instead of ElementName
binding.Path = new PropertyPath(TextBox.VisibilityProperty);
BindingOperations.SetBinding(txt2, TextBox.VisibilityProperty, binding);

grid.Children.Add(txt1);
grid.Children.Add(txt2);
}

关于c# - 当我在运行时添加控件时,以编程方式绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3627705/

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