我有这段代码:
<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/