将StringFormat与XmlDataProvider一起使用

时间:2014-02-03 19:35:56

标签: xml wpf xaml

我正在尝试将StringFormater与XmlDataProvider一起使用而没有成功

<Grid.Resources>
   <XmlDataProvider x:Key="xmlData" XPath="/data" IsAsynchronous="False">
       <x:XData>
         <data xmlns="">
            <AMOUNT1>0.00</AMOUNT1>
         </data>
      </x:XData>
   </XmlDataProvider>
</Grid.Resources>


<TextBox x:Name="DollarAmount1" 
         Text = "{Binding XPath=/data/AMOUNT1, 
         StringFormat={0:C2}}"  
         DataContext="{Binding Source={StaticResource xmlData}}" />

我尝试了以下所有StringFormats,但没有人会将数据重新格式化为货币。有什么建议吗?

StringFormat={0:C2}
StringFormat={}{0:C2}
StringFormat=\{0:C\}

1 个答案:

答案 0 :(得分:0)

XML值是字符串。您正在尝试将字符串格式化为字符串:&gt;

添加一个实现 IValueConverter 的转换器类。

<强> CODE

 public class StringToDoubleConverter : IValueConverter {
    public object Convert(object value, 
                          Type targetType, 
                          object parameter, 
                          System.Globalization.CultureInfo culture) {
      double outValue = 0;
      if (value != null)
      {
        outValue = System.Convert.ToDouble(value);
      }
      return outValue;
    }

    public object ConvertBack(object value, 
                              Type targetType, 
                              object parameter, 
                              System.Globalization.CultureInfo culture) {
      double outValue = 0;
      if (value != null)
      {
        outValue = System.Convert.ToDouble(outValue);
      }
      return outValue;
    }

}

然后将转换器添加到绑定中。

<强> XAML

<TextBox x:Name="DollarAmount1"
             Text="{Binding 
                      Converter={StaticResource StringToDoubleConverter}, 
                      StringFormat=\{0:C\}, 
                      XPath=/data/AMOUNT1}"
                      DataContext="{Binding Source={StaticResource xmlData}}" />