如何绑定DataTemplate中TextBlock的值

本文关键字:DataTemplate TextBlock 的值 绑定 何绑定 | 更新日期: 2023-09-27 18:11:01

嗨,我想绑定一个textBlock的值,这是一个DataTemplate内的textBlock的文本属性将根据文件/文件夹列表改变运行时。我已经写了下面的代码,但字符串空。我的工作环境是Windows Phone 8和Visual Studio 2012。

<Grid x:Name="ContentPanel">
<phone:LongListSelector>    
    <phone:LongListSelector.ListFooterTemplate >
        <DataTemplate >
            <TextBlock  Name="tbfooter" Text="{Binding FooterText, Mode=OneWay}" />
        </DataTemplate>
    </phone:LongListSelector.ListFooterTemplate>
</phone:LongListSelector>  

this textBlock name= tbfooter必须在运行时更新Footertext值。

在后面的代码中,我定义了这个属性,比如

private int _footerText;
public int FooterText
{
   get
   {
      return this._footerText;
   }
   set
   {
      this._footerText=value
      NotifyPropertyChanged("FooterText");
   }
}

然而,textBlock tfooter的值是空的,它不显示任何东西,它只是空。有谁能帮我一下吗?

编辑:我再次更新了XAML代码在这里,。我在这里不关注MVVM,它是一个简单的windows手机应用程序。

如何绑定DataTemplate中TextBlock的值

private int _footerText;
public int FooterText
{
   get
   {
      return this._footerText;
   }
   set
   {
      this._footerText=value;  //  <<-----------You might miss this!
      NotifyPropertyChanged("FooterText");
   }
}

看起来在你的属性设置器中,你需要在通知它的变化之前设置值,请尝试这样做

private int _footerText;
public int FooterText
{
   get
   {
      return this._footerText;
   }
   set
   {  
      this._footerText = value;
      NotifyPropertyChanged("FooterText");
   }
}

当使用DataTemplate时,DataTemplateDataContext是当前选定的项目。如果您将LongListSelector绑定到类型T的List,则可以通过绑定该类型T来访问属性。

你想要绑定到你的Viewmodel的一个属性,它不是当前的DataContext。因为这个原因,你的结果是空的。

试试这个代码

<Grid x:Name="ContentPanel">
<phone:LongListSelector>    
    <phone:LongListSelector.ListFooterTemplate >
        <DataTemplate >
            <TextBlock Name="tbfooter"
                    DataContext="{Binding Path=DataContext,RelativeSource={RelativeSource AncestorType=UserControl}}"
                    Text="{Binding FooterText, Mode=OneWay}" />
        </DataTemplate>
    </phone:LongListSelector.ListFooterTemplate>
</phone:LongListSelector> 

正如inxs所提到的,您的TextBlock是空的,因为它没有绑定到正确的属性。看一下这个答案,它演示了如何绑定到DataContext上的属性和代码隐藏中的属性。