gpt4 book ai didi

c# - 将值传递给 IValueConverter

转载 作者:太空狗 更新时间:2023-10-29 22:22:56 27 4
gpt4 key购买 nike

我有一个 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 中的整个对象,将对象转换为其类型,获取值和键并返回您需要的字符串。

在您的第二个文本 block 上将绑定(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();
}
}

关于c# - 将值传递给 IValueConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16926709/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com