[英]MultiBinding Converter not binding to TextBlock in DataTemplate
我有一個包含多個列的DataGrid
,在其中一個列中,我正在使用MultiBinding
綁定到MultiValueConverter
,但在該列中沒有任何顯示。 我不確定自己在做什么錯。 所述ItemSource
用於DataGrid
, MfrSelection
,不包含對應於所述一個對象VolumeToPercentConverter
。 這是搞砸綁定嗎?
這是相關的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;
}
}
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}"
,可將小數點格式設置為一個很好的百分比。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.