Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't Data Bind to a local variable in WPF/XAML

I want a textbox to display the value of a variable when I click it (an iteration of 1 to 100), I do not know what I am doing Wrong:

When I run the project nothing is displayed in the text box.

What is the best way to display variables in a text box?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace dataBindingTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public string myText { get; set; }

        public void Button_Click_1(object sender, RoutedEventArgs e)
        {
            int i = 0;
            for (i = 0; i < 100; i++)
            {
                myText = i.ToString();
            }
        }
    }
}

XAML:

<Window x:Class="dataBindingTest.MainWindow"
        Name="windowElement"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" Height="106" Margin="71,95,0,0" VerticalAlignment="Top" Width="125" Click="Button_Click_1"/>
        <TextBlock x:Name="myTextBox" HorizontalAlignment="Left" Height="106" Margin="270,95,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="187" Text= "{Binding myText, ElementName=windowElement}" />

    </Grid>
</Window>
like image 819
mzachen Avatar asked Nov 10 '12 20:11

mzachen


1 Answers

Your current myText property has no way of notifying the WPF binding system when its value has changed, so the TextBlock wont be updated.

If you make it a dependency property instead it automatically implements change notification, and the changes to the property will be reflected in the TextBlock.

So if you replace public string myText { get; set; } with all of this code it should work:

public string myText
{
    get { return (string)GetValue(myTextProperty); }
    set { SetValue(myTextProperty, value); }
}

// Using a DependencyProperty as the backing store for myText.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty myTextProperty =
    DependencyProperty.Register("myText", typeof(string), typeof(Window1), new PropertyMetadata(null));
like image 190
Peter Hansen Avatar answered Nov 14 '22 21:11

Peter Hansen