c# - DateTime 的 StringFormat 不适用于 MultiBinding

标签 c# .net wpf multibinding

我有这段代码:

<Label>
    <Label.Content>
        <TextBlock>
            <TextBlock.Text>
                <MultiBinding StringFormat="{} created on {0} by">
                    <Binding Path="CreationDate" StringFormat="{}{0:dd/MM/yyyy}" />
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </LabeledLabel.Content>
</Label>

输出

我总是得到这个创建于 21/09/2014 00:00:00 的

我尝试了 StringFormat="d",但它也没有用。

我的代码有什么问题?

最佳答案

您只有一个绑定(bind)路径,因此您只会获得日期和时间。基本上,您需要为个人数据类型添加一个 Binding 元素。它应该更像这样:

<Label>
    <Label.Content>
        <TextBlock>
            <TextBlock.Text>
                <MultiBinding StringFormat="{} created on {0:dd/MM/yyyy} by {1}">
                    <Binding Path="CreationDate" />
                    <Binding Path="SomeEmployeeObject.Name" />
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </LabeledLabel.Content>
</Label>

请注意,您还可以使用 MultiBinding.StringFormat 属性设置 DateTime StringFormat,而不是在第一个 Binding 对象上添加另一个。您还需要将 {1} 添加到 MultiBinding.StringFormat 的末尾,以便它输出第二个(与人相关的)值。

请参阅MultiBinding Class MSDN 上的页面以获取更多信息。


更新>>>

I don't understand why putting the StringFormat property on the MultiBinding element has a different behaviour compared to the first element

它没有...我本可以把它留在那儿,但我移动了它,因为您已经在使用 StringFormat。在 MultiBinding 上使用 StringFormat 属性实际上与使用 string.Format 方法相同。使用该方法,这等同于您在 XAML 中的内容:

string.Format("created on {0:dd/MM/yyyy} by ", someDate);

这等同于我放入您的 XAML 中的内容:

string.Format("created on {0:dd/MM/yyyy} by {1}", someDate, someEmployee.Name);

希望您现在可以看出区别。

关于c# - DateTime 的 StringFormat 不适用于 MultiBinding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25385488/

相关文章:

c# - 如何解决这个递归异步/等待问题?

.NET ZIP 库在内存中工作

wpf - 关于 CapsLock 的警告

c# - Application.Run(new Form1()) 抛出 System.ArgumentException : 'Value does not fall within the expected range.'

.net - 始终在 DAL 基类中使用 TransactionScope 是一个好习惯吗?

.net - 将多选 ListBox 与 MVVM 同步

c# - 在代码中将 DataTemplate(非 XAML)添加到资源字典?

c# - 如何使用触摸将元素拖出可滚动的 ListView,而无需按住元素 [UWP]

c# - 使用NEST客户端将过滤器添加到elasticsearch的搜索查询中

c# - 使用 string.Format ("{0:00}"格式化字符串