2017-03-04 126 views
0

我想将视图模型中的字符串绑定到DataGridTextColumn的StringFormat属性。但是,我下面有什么不起作用。有没有办法做到这一点,而不使用转换器或资源?如果不是,那么最简单的方法是什么?DataGridTextColum绑定StringFormat

<DataGridTextColumn Binding="{Binding Date, StringFormat={Binding DateFormat}}" /> 

回答

2

因为Binding类不从DependencyObject继承您不能结合什么的Binding性能。

ContentControl(例如Label)派生的控件具有您可以绑定的ContentStringFormat属性。如果DataGridTextColumn派生自ContentControl,那么这将解决您的问题,但事实并非如此。

你可以把它包含Label一个DataTemplate一个DataGridTemplateColumn,并结合Label.ContentStringFormatDateFormat属性:

<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(); 
    } 
} 
+1

你的回答是完美的。我删除了我的。谢谢。 – Ron

+0

格式化线有问题吗?它的格式不正确。为我的“3/6/2017 2:28:26 AM”提供格式字符串。尽管答案的其余部分完美。 –

+0

@TerryAnderson我不明白。如果你说它不是根据格式字符串格式化日期,那么它没有做任何完美的事情 - 事实上它什么都不做。代码从我的工作测试用例中复制并粘贴。让我再次检查格式字符串。 –

相关问题