question

LoganStach-1629 avatar image
0 Votes"
LoganStach-1629 asked LoganStach-1629 commented

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

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?

windows-uwp
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hello, does my reply solve your problem? Do you have any other questions?

0 Votes 0 ·

Hi,
Yes, it does solve my problem. Sorry for the delayed response. Thank you very much.

0 Votes 0 ·

1 Answer

RichardZhang-MSFT avatar image
0 Votes"
RichardZhang-MSFT answered

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.