kknaguib
kknaguib

Reputation: 749

Binding textblock text to property on load

I'm trying to display the number of records retrieved by the query after the window loads. Here's what I have in my XAML:

<TextBlock Name="numRecordsAnalyzed_TAtab" TextWrapping="Wrap" Margin="12,0,0,4" Grid.RowSpan="2"> 
                        <Run Text="Records Found: " Foreground="{StaticResource Foreground}" FontSize="12"/>
                        <Run Text="{Binding Numrecords}" Foreground="Red" FontSize="12"/>
    </TextBlock>

Here's my c#:

private int numOfrecords = 0;
public event PropertyChangedEventHandler PropertyChanged;

    public string Numrecords
    {
        get { return Convert.ToString(numOfrecords); }
        set
        {
            OnPropertyChanged("NumOfrecords");
        }
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

Then I add this to get the number of records and when I debug I see that the variable holds the number and everything but nothing is displayed in the window when the window launches:

numOfrecords = OpenTradesQuery.Count();

What am I missing?

Upvotes: 0

Views: 113

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81243

You need to raise PropertyChanged event to notify GUI to update.

Declare property of type int, WPF will automaically call ToString() on your property, you need not to worry about that.

public int Numrecords
{
    get { return numOfrecords; }
    set
    {
        if(numOfrecords != value)
        { 
           numOfrecords = value;
           OnPropertyChanged("Numrecords");
        }
    }
}

Set the property:

Numrecords = penTradesQuery.Count();

You can set DataContext in code behind after InitializeComponent() in constructor of Window/UserControl:

DataContext = this;

Also, you can set it in XAML at root level like this:

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}"/>

Upvotes: 2

Related Questions