【问题标题】:Format DateTime dependency Property as text (String)将 DateTime 依赖属性格式化为文本(字符串)
【发布时间】:2012-04-19 13:22:11
【问题描述】:

编辑:尝试实现转换器时 Gettign Xaml 解析错误

错误:Provide value on 'System.Windows.Markup.StaticResourceHolder' 引发异常。

<DataTemplate>
                    <myClasses:RegistrationButton x:Name="RegistrationButton" HorizontalAlignment="Center" Height="71" Width="148" 
                                                  Margin="10,0,5,0" 
                                                  Style="{DynamicResource ButtonStyleRegistration}"
                                                  Click="RegistrationButton_Click"
                                                  Title="{Binding Title}"
                                                  Oorzaak="{Binding Oorzaak}"

                                                  DuurStilstand="{Binding DuurStilstand, 
                                                        Converter={StaticResource DateTimeConvertor},  
                                                        ConverterParameter=\{0:t\}}"

                                                  BeginStilstand="{Binding BeginStilstand}"
                                                  />
                </DataTemplate>

IValue 转换器:

    public class DateTimeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Retrieve the format string and use it to format the value.
        string formatString = parameter as string;
        if (!string.IsNullOrEmpty(formatString))
        {
            return string.Format(culture, formatString, value);

        }
        // If the format string is null or empty, simply call ToString()
        // on the value.
        return value.ToString();
    }

    // No need to implement converting back on a one-way binding 
    public object ConvertBack(object value, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

目前我有一个使用绑定并显示正确的字符串依赖属性。虽然这个属性应该是 DateTime 。我在整个应用程序中都使用字符串进行计算,这应该使用一个 DateTime 值来代替。

当我尝试将其更改为 DateTime 时,除了绑定错误之外什么都没有。之前属性是字符串类型。

public static readonly DependencyProperty DuurStilstandProperty =
        DependencyProperty.Register("DuurStilstand", typeof(DateTime), typeof(RegistrationButton), new UIPropertyMetadata(""));

public DateTime DuurStilstand
    {
        get { return (DateTime)GetValue(DuurStilstandProperty); }
        set { SetValue(DuurStilstandProperty, value); }
    }

XAML 绑定:

<TextBlock x:Name="tbDuurStilstand" TextWrapping="Wrap" 
                                   Text="{Binding DuurStilstand, UpdateSourceTrigger=PropertyChanged}" 
                                   HorizontalAlignment="Center"
                                   VerticalAlignment="Center" 
                                   Margin="7.5,5,0,0" Height="24.8266666666667"/>

<ListBox.ItemTemplate>
                <DataTemplate>
                    <myClasses:RegistrationButton x:Name="RegistrationButton" HorizontalAlignment="Center" Height="71" Width="148" 
                                                  Margin="10,0,5,0" 
                                                  Style="{DynamicResource ButtonStyleRegistration}"
                                                  Click="RegistrationButton_Click"
                                                  Title="{Binding Title}"
                                                  Oorzaak="{Binding Oorzaak}"
                                                  DuurStilstand="{Binding DuurStilstand}"
                                                  BeginStilstand="{Binding BeginStilstand}"
                                                  />
                </DataTemplate>
            </ListBox.ItemTemplate>

此处显示错误 (XamlParseException):

<myClasses:RegistrationButton x:Name="btnTestRegistration" Content="Test Registratie" HorizontalAlignment="Left" Margin="16.8,0,0,118.14" 
            VerticalAlignment="Bottom" Width="119.2" Height="30.2" FontSize="18.667" Click="btnTestRegistration_Click" Style="{DynamicResource ButtonStyleRegistration}" />

为什么我无法将其更改为 DateTime。

文本块需要一个字符串而不是它当前正在获取的 DateTime。当内容放置在文本块的 .text 属性中时,我如何确保它将 DateTime 转换为字符串?

最好的问候,彼得P

【问题讨论】:

    标签: c# .net wpf xaml


    【解决方案1】:

    在我看来,在这种情况下,最好的解决方案是使用Binding Converters 与绑定数据进行交互。

    public class DateTimeConverter: IValueConverter
    {
            public object Convert(object value, Type targetType, object parameter, CultureInfo 
            {
    
               DateTime dt = (DateTime)value;
               //convert back to string from dt 
    
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
              string dateTimeString = value as string; 
    
               //Convert to DateTime from dateTimeString 
            }
        }
    

    定义 ins 说 App.xaml

    <DateTimeConverter x:Key="DateTimeConverter" />
    

    并绑定到您的属性

    <myClasses:RegistrationButton x:Name="RegistrationButton" HorizontalAlignment="Center" Height="71" Width="148" 
                                                      Margin="10,0,5,0" 
                                                      Style="{DynamicResource ButtonStyleRegistration}"
                                                      Click="RegistrationButton_Click"
                                                      Title="{Binding Title}"
                                                      Oorzaak="{Binding Oorzaak}"
                                                      DuurStilstand="{Binding DuurStilstand}"
                                                      BeginStilstand="{Binding BeginStilstand}"
                                                      Converter = {StaticResource DateTimeConverter }
    
    
                            />
    

    【讨论】:

    • 你好蒂格兰。在 Convert 中 Convert to Formatstring 不是相反,还是我弄错了?有点困惑在这里返回什么(hh:mm:ss)。
    • @PeterP:你是对的。刚刚更正,错字错误..太快了。
    • 我尝试实现但我得到一个解析错误,我不知道是什么原因。将在帖子顶部发布一些短代码。我到底做错了什么?今天早些时候尝试实现一个转换器,但由于 xmal 解析错误,我也失败了。最好的问候。
    • @PeterP:在我看来,在 Convert 你得到一个字符串,但也返回一个字符串!您必须返回 DateTime,因为绑定属性是 DateTime(至少基于您的帖子)
    • 嗯,我当前的属性是 DateTime,我希望将其转换为绑定属性中的字符串。我很困惑:/我的应用程序现在一直在崩溃。你能告诉我究竟要返回什么,因为我不明白 atm 吗?干杯。 /彼得
    【解决方案2】:

    好吧,当您谈论转换(从 DateTime 到字符串)时,您可以简单地将 IValueConverter 添加到您的绑定中。以下 MSDN 文章有一个示例,展示了如何将 DateTime 转换为字符串:

    http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter(v=vs.95).aspx

    【讨论】:

      【解决方案3】:

      我认为你的问题在这里:

      public static readonly DependencyProperty DuurStilstandProperty =
              DependencyProperty.Register("DuurStilstand", typeof(DateTime), typeof(RegistrationButton), new UIPropertyMetadata(""));
      

      您可以使用 DateTime,但 WPF 将需要强制提供给 DateTime 的值,而您的 UIPropertyMetadata([defaultvalue]) 是一个空字符串,无法强制转换为 DateTime。你应该使用类似 `UIPropertyMetadata(DateTime.MinValue) 的东西。

      另外,我建议您将IValueConverters 应用于您的绑定,这样您就不会依赖 WPF 来强制字符串,这很可能是不可强制的,而是在转换器中有一些逻辑来妥善处理事情。

      【讨论】:

        【解决方案4】:

        在您的属性定义中,您将默认值设置为空字符串。显然这对于​​ DateTime 是无效的!您需要提供一个实际上与属性类型兼容的默认值。

        试试这个:

        public static readonly DependencyProperty DuurStilstandProperty =
            DependencyProperty.Register("DuurStilstand", typeof(DateTime), typeof(RegistrationButton), new UIPropertyMetadata(DateTime.MinValue));
        

        您可以将 MinValue 替换为任何对您有意义的默认值(可能是 DateTime.Now)。

        要在绑定日期时实际格式化日期,您可以使用 StringFormat 或转换器,正如其他人所建议的那样。

        编辑

        根据您使用转换器的问题。您需要创建转换器的实例,然后您可以引用它。例如,您可以这样做:

        <Window.Resources>
            <local:DateTimeConverter x:Key="MyConverter"/>
        </Window.Resources>
        

        然后像这样使用它:

        DuurStilstand="{Binding DuurStilstand, 
              Converter={StaticResource MyConverter},  
              ConverterParameter=\{0:t\}}"
        

        【讨论】:

          猜你喜欢
          • 2014-11-30
          • 1970-01-01
          • 2023-04-09
          • 2020-01-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多