Ross
Ross

Reputation: 325

WPF Binding to String value to TextBlock

I am just getting started with WPF and I am trying to understand binding.

I Have a method called GetVersion() that returns a value of 1.2.3.2 I need to bind this return data to a TextBlock so the 1.2.3.2 is returned to the main window.

My MainWindow.xaml.cs looks like this:

 public MainWindow()
    {
        InitializeComponent();
        GetSequoiaVersion getApiVersion = new GetSequoiaVersion();
        _value = getApiVersion.GetApiVersion();
        myTextBlock.DataContext = Value;
    }
    private string _value;
    public string Value
    {
        get 
        {
            return _value;

        }
        set
        {
            _value = value;
        }
....................

If I debug the program the DataContext = Value does show the value of 1.2.3.2

My current XAML code looks like this

  <Grid>
    <StackPanel Name="Display">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="API Version: " />
            <TextBlock x:Name="myTextBlock" Margin="200,0,0,0" Text="{Binding Value}" />
        </StackPanel>
    </StackPanel>                   
</Grid>

Once again the return data is passed to the DataContext Value (hovering the mouse displays the 1.2.3.2 as expected but this is were it falls over, the form loads but no data is displayed in my text block that is bound to the DataContext

Any help please

Upvotes: 1

Views: 2123

Answers (1)

CharlesMighty
CharlesMighty

Reputation: 572

your MainWindow.xaml.cs should look like this

public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
        DataContext = ApiVersion.GetApiVerision();

    }

}


public class ApiVersion
{
    public string Version { get; set; }

    public static ApiVersion GetApiVerision()
    {

        var version = new ApiVersion() {Version = "1.2.3.2"};

        return version;
    }
}

And your MainWindow.xaml should look like this

 <Window x:Class="TestWPF.MainWindow"
    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>

    <TextBlock Name="myTextBlock"
               Text="{Binding Version}" />

</Grid>

Upvotes: 1

Related Questions