C# 和 XAML Windows 应用商店应用如何更改文本块数据?



我可以在DataTemplate中更改textBlockZona的值吗? 我需要创建一个动态标题列表,如何更改代码中的myTEXT内容?

<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" />

您应该将TextBlockText属性绑定到已设置为ListViewItemsSourceIEnumerable<T>T类型的属性:

<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" />

然后,您可以简单地将此属性设置为所需的任何字符串,并自动更新TextBlock,前提是类型T实现INotifyPropertyChanged接口:https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx。

这是执行此操作的唯一正确方法。不要以编程方式修改在 XAML 标记中定义的模板

编辑:HeaderTemplate中的TextBlock应以相同的方式绑定到视图模型中的属性,即ListView本身的DataContext

最新更新