CriMig8 CriMig8 -4 years ago 99
C# Question

C# and XAML Windows Store App How change textBlock data?

Can I change the values of textBlockZona in DataTemplate?
I need to create a dynamic header list, how can I change myTEXT content in the code?

<Page.Resources>
<DataTemplate x:Key="HeadTemplate">
<Grid
Width="745" Height="61" HorizontalAlignment="Left" VerticalAlignment="Top" AllowDrop="True" Background="Transparent">

<Grid
x:Name="gridZona" Width="122" Height="36" Margin="0,10,0,0" HorizontalAlignment="Left" VerticalAlignment="Top">
<Rectangle x:Name="ZonaButton" Fill="#FF2994FF" />
<TextBlock
x:Name="textBlockZona" Margin="0,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" Foreground="White"
Text="MYTEXT"
TextAlignment="Center" TextWrapping="Wrap" d:LayoutOverrides="TopPosition, BottomPosition" />
</Grid>

</DataTemplate>

<DataTemplate x:Key="ViewTemplate">
<local:PosItemViewer />
</DataTemplate>

</Page.Resources>

<ListView x:Name="RigheView" Grid.Row="1" Width="744" Height="867" Margin="10,203,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"
ContainerContentChanging="RigheView_ContainerContentChanging"
HeaderTemplate="{StaticResource HeadTemplate}"
IsItemClickEnabled="True"
ItemTemplate="{StaticResource ViewTemplate}"
SelectionMode="None" />

Answer Source

You should bind the Text property of the TextBlock to a property of the type T in the IEnumerable<T> that you have set as the ItemsSource of the ListView:

<TextBlock x:Name="textBlockZona" Text="{Binding YourTextProperty}" Margin="0,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" Foreground="White" TextAlignment="Center" TextWrapping="Wrap" d:LayoutOverrides="TopPosition, BottomPosition" />

Then you can simply set this property to any string you want and have the TextBlock being automatically updated provided that the type T implements the INotifyPropertyChanged interface: https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx.

This is the only correct way of doing this. You don't modify a template that you have defined in your XAML markup programmatically.

Edit: A TextBlock in the HeaderTemplate should be bound to a property in the view model, i.e. the DataContext of the ListView itself, the same way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download