我想將視圖模型中的字符串綁定到DataGridTextColumn的StringFormat屬性。但是,我下面有什麼不起作用。有沒有辦法做到這一點,而不使用轉換器或資源?如果不是,那麼最簡單的方法是什麼?DataGridTextColum綁定StringFormat
<DataGridTextColumn Binding="{Binding Date, StringFormat={Binding DateFormat}}" />
我想將視圖模型中的字符串綁定到DataGridTextColumn的StringFormat屬性。但是,我下面有什麼不起作用。有沒有辦法做到這一點,而不使用轉換器或資源?如果不是,那麼最簡單的方法是什麼?DataGridTextColum綁定StringFormat
<DataGridTextColumn Binding="{Binding Date, StringFormat={Binding DateFormat}}" />
因爲Binding
類不從DependencyObject
繼承您不能結合什麼的Binding
性能。
從ContentControl
(例如Label
)派生的控件具有您可以綁定的ContentStringFormat
屬性。如果DataGridTextColumn
派生自ContentControl
,那麼這將解決您的問題,但事實並非如此。
你可以把它包含Label
一個DataTemplate
一個DataGridTemplateColumn
,並結合Label.ContentStringFormat
您DateFormat
屬性:
<DataGridTemplateColumn Header="Date Template">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Label
Content="{Binding Date}"
ContentStringFormat="{Binding DataContext.DateFormat,
RelativeSource={RelativeSource AncestorType=DataGrid}}"
/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
但是,當我改變視圖模型的DateFormat
屬性,不更新。我不知道爲什麼,可能我做錯了什麼。
這給我們留下了一個多值轉換器。當我更改視圖模型的DateFormat
屬性(兩個相鄰的列,一個更新,另一個不更新 - 所以沒有人告訴我我沒有提升PropertyChanged
)時,它會更新。
<Window.Resources>
<local:StringFormatConverter x:Key="StringFormatConverter" />
</Window.Resources>
...等等等等等等...
<DataGridTextColumn
Header="Date Text"
>
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource StringFormatConverter}">
<Binding Path="Date" />
<Binding
Path="DataContext.DateFormat"
RelativeSource="{RelativeSource AncestorType=DataGrid}" />
</MultiBinding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
C#:
這將適用於任何字符串格式爲任意值,而不僅僅是一個DateTime
。我的DateFormat
屬性返回"{0:yyyy-MM-dd}"
。
此轉換器上的第一個綁定是您要格式化的值。第二個綁定是format string parameter for String.Format()
。上面的格式字符串在格式化字符串之後採用「第0個」參數 - 即{0}
- 並且如果該值爲DateTime
,則使用四位數年份,短劃線,兩位數月份,短劃線和兩位數的一天。 DateTime
格式字符串是自己的主題; here's the MSDN page on the subject。
我給你的是最簡單的書寫方式,而且是最強大的。您可以傳遞一個雙精度數字並給它一個格式字符串,如"My cast has {0:c} toes"
,如果雙精度爲3.00999
,它會告訴你它的貓有$3.01
腳趾。
但是,在給予您所有String.Format()
的權力後,我在編寫格式化字符串的過程中有點複雜。這是一個折衷。
public class StringFormatConverter : IMultiValueConverter
{
public object Convert(object[] values,
Type targetType, object parameter, CultureInfo culture)
{
return String.Format((String)values[1], values[0]);
}
public object[] ConvertBack(object value,
Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
你的回答是完美的。我刪除了我的。謝謝。 – Ron
格式化線有問題嗎?它的格式不正確。爲我的「3/6/2017 2:28:26 AM」提供格式字符串。儘管答案的其餘部分完美。 –
@TerryAnderson我不明白。如果你說它不是根據格式字符串格式化日期,那麼它沒有做任何完美的事情 - 事實上它什麼都不做。代碼從我的工作測試用例中複製並粘貼。讓我再次檢查格式字符串。 –