我有一个ListView
,其中有两列多行的Grid
。每行在每一列中都有一个TextBlock
,每个Text
属性都绑定(bind)到ListView的ItemSource
中的值。我需要根据第一个TextBlock
中的值对第二个TextBlock
中的文本进行一些转换。如何获得第一个文本框的值到转换器?
这是我到目前为止的内容:
XAML:
<UserControl.Resources>
<local:ValueStringConverter x:Key="valueStringConverter" />
</UserControl.Resources>
<ListView Name="theListView" ItemsSource="{Binding ItemCollection}" SelectedItem="{Binding SelectedItem}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Grid.Row="1" >
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Path=Key}" Grid.Column="0" Margin="0,0,10,0" />
<TextBlock Text="{Binding Path=Value, Converter={StaticResource valueStringConverter}}" TextWrapping="Wrap" Grid.Column="1" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
ValueStringConverter
的代码:public class ValueStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string name = (string)value;
name = name.Replace("$$", " ");
name = name.Replace("*", ", ");
name = name.Replace("##", ", ");
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
最佳答案
您不能将多个值传递给“常规”值转换器。您可以使用IMultiValueConverter并将绑定(bind)定义为MultiBinding。
或者,您可以创建一个IValueConverter,该对象将DataContext中的整个对象用作对象,将对象转换为其类型,获取Value和Key并返回所需的字符串。
在第二个文本块上,将绑定(bind)定义为
<TextBlock Text="{Binding Converter={StaticResource valueStringConverter}"/>
和您的转换器为:
public class ValueStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
MyDataContextObjectType obj= (MyDataContextObjectType)value;
var name= obj.Name;
var key = obj.Key;
//here you have both Name and Key, build your string and return it
//if you don't know the type of object in the DataContext, you could get the Key and Name with reflection
name = name.Replace("$$", " ");
name = name.Replace("*", ", ");
name = name.Replace("##", ", ");
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}