Search code examples
c#xamluwpuwp-xamltextblock

TextBlock should have an input from code (xaml, c#)


in an .XAML I wrote

<TextBlock> x words found </TextBlock>

and in my .cs I wrote something like this:

public int number(A a, B b) {
    […]
    return resultsCount;
}

I want x to be resultsCount in this case. How do I link it so x becomes a number of resultsCount?


Solution

  • the simplest solution:

    You can set your TextBlock like this:

    <TextBlock >
        <Run x:Name="MyRun" Text="0"/> // place for the 'X' of your code
        <Run Text="words found"/>
    </TextBlock>
    

    and in the codebehind, you can change the Text of MyRun in your int number(A a, B b) method like this:

    public int number(A a, B b)
    {
        […]
        MyRun.Text = resultsCount.ToString();
        return resultsCount;
    
    }
    

    Solution that involves data binding:

    in this case you should define a property that raises PropertyChanged event on change like this:

    public class CodeBehind : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        private string simpleString;
        public string SimpleString
        {
            get{ return simpleString; }
            set
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SimpleString"));
                simpleString = value;
            }
        }
        public int number(A a, B b)
        {
            […]
            return resultsCount;
    
        }
    }
    

    and then simply bind the Text property of MyRun with this SimpleString Property:

    <TextBlock >
        <Run x:Name="MyRun" Text="0"/>
        <Run Text="words found"/>
    </TextBlock>
    

    Whenever you need to update that "X", in code behind, just do this:

    SimpleString = number(a,b).ToString();