2014-09-03 63 views
1

我有一个DataGrid多列,我在其中一列使用MultiBinding绑定到MultiValueConverter,但没有显示在该列中。我不确定我做错了什么。对于DataGrid,MfrSelectionItemSource不包含对应于VolumeToPercentConverter的对象。这是什么搞乱了绑定?MultiBinding转换器不绑定到DataTemplate中的TextBlock

下面是相关的XAML

<Window.Resources> 
     <local:VolumeToPercentConverter x:Key="VolumeToPercentConverter"/> 
    </Window.Resources> 
    ...   
<DataGrid x:Name="_mfrSelectionGrid" Grid.ColumnSpan="2" Grid.Row="2" ItemsSource="{Binding MfrSelection}" Margin="5,0" AutoGenerateColumns="False"> 
    ... 
        <DataGridTemplateColumn x:Name="_PercentChange" IsReadOnly="True" Visibility="Visible" Header="Percent Change"> 
         <DataGridTemplateColumn.CellTemplate> 
          <DataTemplate> 
           <TextBlock Margin="3,0" VerticalAlignment="Center"> 
            <TextBlock.Text> 
             <MultiBinding Converter="{StaticResource VolumeToPercentConverter}"> 
              <Binding Path="YearVolume"/> 
              <Binding Path="LastYearVolume"/> 
             </MultiBinding> 
            </TextBlock.Text> 
           </TextBlock> 
          </DataTemplate> 
         </DataGridTemplateColumn.CellTemplate> 
        </DataGridTemplateColumn> 

而且在我的代码转换器背后:

public class VolumeToPercentConverter : IMultiValueConverter 
{ 
    public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture) 
    { 
     decimal percent = 0; 
     if (value[0] is decimal && value[1] is decimal) 
     { 
      if ((decimal)value[1] != 0 && (decimal)value[0] != 0) 
      { 
       percent = ((decimal)value[0] - (decimal)value[1])/(decimal)value[1]; 
       return percent; 
      } 
      else 
      { 
       return percent; 
      } 
     } 
     else 
     { 
      return percent; 
     } 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) 
    { 
     return null; 
    } 
} 
+0

有什么问题?是否将值传递给转换器null? – 2014-09-03 17:50:02

回答

4

的VolumeToPercentConverter返回一个十进制值,但TextBlock.Text属性期待一个字符串。这是我在输出窗口收到的时候我创建了一个测试项目中的错误:

Value produced by BindingExpression is not valid for target property.; Value='1' MultiBindingExpression:target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') 

我通过更新XAML如下解决了这个:

<MultiBinding Converter="{StaticResource VolumeToPercentConverter}" StringFormat="{}{0:P}"> 
    <Binding Path="YearVolume"/> 
    <Binding Path="LastYearVolume"/> 
</MultiBinding> 

的秘诀是格式化的StringFormat="{}{O:P}"十进制成很好的百分比。