How do I assign a variable to a Textblock within a DataTemplate in a ListViewHeader?

Logan Stach 41 Reputation points
2020-02-16T20:55:22.473+00:00

I have a DataTemplate inside a ListViewHeader with a Textblock inside it. I want this Textblock to have a string variable that I give it in code in the cs file. However, because it's in a DataTemplate, the Textblock is not recognized in the cs file. So, how do I assign the textblock's text property a variable's value?

Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. Richard Zhang-MSFT 6,936 Reputation points
    2020-02-17T05:39:55.94+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    You can assign the variable to ListView.Header:

    xaml

    <ListView.HeaderTemplate>

    <DataTemplate>

    <TextBlock Text="{Binding}" Foreground="Red"/>

    </DataTemplate>

    </ListView.HeaderTemplate>

    xaml.cs

    TestListView.Header = "Test";
    

    If you need to set the header using bindings, in order to change the UI when you change the variable, you need to implement the INotifyPropertyChanged interface:

    public sealed partial class MainPage : Page, INotifyPropertyChanged
    {
        private string _testHeader;
        public string TestHeader
        {
            get => _testHeader;
            set
            {
                _testHeader = value;
                OnPropertyChanged();
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName]string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    
        // ....
    }
    

    Usage

    <ListView x:Name="TestListView" Header="{x:Bind TestHeader,Mode=OneWay}" ... >
    ...
    </ListView>

    Thanks.

    0 comments No comments

0 additional answers

Sort by: Most helpful