2

我需要通过以下方式将 TextBlock.Text 与 TimeSpan 类型的 SumOfPeriods 属性绑定:

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0:D1} h {1:D1} min ({2:D1} min)">
            <Binding Path="SumOfPeriods.Hours" />
            <Binding Path="SumOfPeriods.Minutes" />
            <Binding Path="SumOfPeriods.TotalMinutes" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

...但它不起作用。内容不显示。当我删除对 TotalMinutes 的绑定时,它可以工作并显示内容:

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0:D1} h {1:D1} min">
            <Binding Path="SumOfPeriods.Hours" />
            <Binding Path="SumOfPeriods.Minutes" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

任何人都可以帮助我吗?

4

2 回答 2

4

TotalMinutes是 a Double,但D格式说明符仅支持整数类型,例如Int32. 格式字符串{}{0:D1} h {1:D1} min ({2} min)应该可以工作。

于 2013-04-27T21:15:20.377 回答
0

转换器可以解决您的问题:

public class PeriodConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var timeSpan = (TimeSpan)value;

        // add your format here
        var text = string.Format("", timeSpan);

        return text;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Binding.DoNothing;
    }
}

将转换器添加到您的资源中:

<FrameworkElement.Resources>
    <converters:PeriodConverter x:Key="periodConverter" />
</FrameworkElement.Resources>

更新 TextBlock 的绑定:

<TextBlock Text={Binding Path=SumOfPeriods, Converter={StaticResource periodConverter}} />
于 2013-04-27T23:23:43.883 回答