WPF Binding to local variable

Viewed 97371

Can you bind to a local variable like this?

SystemDataBase.cs

namespace WebWalker
{
    public partial class SystemDataBase : Window
    {
        private string text = "testing";
...

SystemDataBase.xaml

 <TextBox 
       Name="stbSQLConnectionString" 
       Text="{SystemDataBase.text}">
 </TextBox>

??

Text is set to the local variable "text"

5 Answers

Need to add the following line in the int constructor:

this.DataContext = this;

And use this in the XAML:

<TextBox Text = "{Binding SomeProperty}" />

Exmaple:

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public string PersonName { get; set; }

    public MainWindow()
    {
        InitializeComponent();            
        PersonName = "default";
        this.DataContext = this;
    }

    void button1_Click(object sender, RoutedEventArgs args)
    {            
        MessageBox.Show($"Hello {PersonName}");
    }
}

MainWindow.xaml

<StackPanel>
        <TextBox Name="textbox1" 
                 Text="{Binding PersonName, Mode=TwoWay}"
                 />
        <Button Name="button1" Click="button1_Click" Content="Click Me" />
</StackPanel>
Related