Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

[WPF] How to bind in XAML to an object created in code behind?

$
0
0

Goal: Bind in XAML to an object created in code behind.

Problem: Binding doesn't work.

Notes:

1. It works, if the object is created in XAML.

2. RegisterName is used.

Question: How to bind in XAML to an object created in code behind in the way illustrated in the following example?

MainWindow.xaml:

<StackPanel x:Name="stackPanel" Background="Black" MouseDown="StackPanel_MouseDown"><TextBox x:Name="textBox" Text="{Binding ElementName=ok, Path=Text, Mode=OneWay}"/></StackPanel>

MainWindow.xaml.cs:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void StackPanel_MouseDown(object sender, MouseButtonEventArgs e)
        {
            TextBox textBox = new TextBox();
            this.RegisterName("ok", textBox);
            stackPanel.Children.Add(textBox);
        }
    }

Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>