【问题标题】:Does StringFormat work with this.DataContextStringFormat 是否与 this.DataContext 一起使用
【发布时间】:2011-01-25 06:36:10
【问题描述】:

我通过 this.DataContext = SellerList; 将 TextBlock 与代码隐藏中的集合绑定。 输出是正确的,但是当我应用 StringFormat 时,我看不到任何结果。以下是xaml页面上TextBlock的代码

<TextBlock Name="dateDTKey" Grid.Row="1" Grid.Column="2" HorizontalAlignment="Right" VerticalAlignment="Bottom" 
      Text="{Binding Path=Date, StringFormat={}{0:dd-MM-yyyy}}" 
      Style="{StaticResource textStyleTextBlock}"/>

【问题讨论】:

  • 非常抱歉 真的很抱歉因为我的愚蠢而打扰你们。 实际上我正在将日期类型的值读入字符串属性而不是日期时间。因为这个格式没有被应用。版主可以随意删除这个问题,我再次为愚蠢道歉。

标签: wpf xaml string-formatting


【解决方案1】:

Binding 的来源是一个字符串,如果detailsSellerListingTemplate 是一个资源,你应该使用{StaticResource detailsSellerListingTemplate}。此外,TextBlock 不需要 DataContext 即可使此 Binding 工作,因为它使用 Source。

<Window.Resources>
    <local:DetailsSeller x:Key="detailsSellerListingTemplate"/>
</Window.Resources>
<TextBlock Name="dateDTKey"
           HorizontalAlignment="Right"
           VerticalAlignment="Bottom"
           Text="{Binding Source={StaticResource detailsSellerListingTemplate},
                          Path=Date,
                          StringFormat={}{0:dd-MM-yyyy}}"/>

如果DetailsSeller 看起来与此相似,这将起作用

public class DetailsSeller
{
    public DetailsSeller()
    {
        Date = DateTime.Now;
    }

    public DateTime Date
    {
        get;
        set;
    }
}

您谈到了一个集合,但我看不出它如何与绑定相匹配,所以我可能误解了问题中的某些内容

【讨论】:

  • 非常抱歉......我在问题中编码错误......已经更新......我正在绑定 this.DataContext = SellerList。
【解决方案2】:

我认为这是因为您可以使用字符串格式的许多大括号。试试这个:

StringFormat={0:dd-MM-yyyy}

【讨论】:

  • 这不是因为这个......因为相同的代码适用于 Listview.DataContext 绑定到集合而不是 this.Datacontext 的 listview 的 GridViewColumns
  • 我试过这样做dateDTKey.DataContext = SellerList。可能是其他问题
  • 好吧,通常 TextBlock 绑定到单个项目而不是集合,这可能会导致问题。
  • 不,您可以将文本块绑定到数据上下文。如果它不起作用,我将能够看到任何结果。只是格式不适用
猜你喜欢
  • 1970-01-01
  • 2010-11-03
  • 2012-04-13
  • 2018-12-15
  • 2012-03-09
  • 2020-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多