Xamarin Forms ConverterParameter-如何引用当前项属性?
我的目标如下:Xamarin Forms ConverterParameter-如何引用当前项属性?,xamarin,xamarin.forms,Xamarin,Xamarin.forms,我的目标如下: public class MyObj { public string Name {get; set;} public double Weight {get; set;} } 我从这个类中创建了一个ObservableCollection对象,并将其分配给ListView的ItemsResource(下面是lvMyObjs)。我也有一个条目 我需要对ListView中的每一行执行以下操作 从条目中获取值并将其传递给转换器 将输入值与转换器中当前项的权重属性相乘 在我的l
public class MyObj {
public string Name {get; set;}
public double Weight {get; set;}
}
我从这个类中创建了一个ObservableCollection对象,并将其分配给ListView的ItemsResource(下面是lvMyObjs)。我也有一个条目
我需要对ListView中的每一行执行以下操作
- 从条目中获取值并将其传递给转换器
- 将输入值与转换器中当前项的权重属性相乘
- 在我的listview的相应行中显示值李>
<Entry x:Name="entSourceValue"/>
<ContentPage.Resources>
<ResourceDictionary>
<local:SourceToTargetConverter x:Key="myConverter" />
</ResourceDictionary>
</ContentPage.Resources>
<ListView x:Name="lvMyObjs">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ContentView>
<Frame>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" />
<Label x:Name="lblResult"
Text="{
Binding Text,
Converter={StaticResource myConverter},
ConverterParameter={},
Source={x:Reference entSourceValue}
}"/>
</StackLayout>
</Frame>
</ContentView>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
public class SourceToTargetConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double sourceDouble;
double.TryParse((string)value, out sourceDouble);
//todo: convert parameter to double
//double weight =
return sourceDouble * weight;
}
}
我可以在转换器中获得我输入的值,没有任何问题。我的问题是如何将listview中当前项的“权重”作为参数发送到转换器?换言之,我应该在队列中添加什么
“转换器参数={},”
非常感谢您的帮助 您可以将
MyObj
传递到转换器中,然后使用x:Reference
作为条目的参数
<Label x:Name="lblResult" Text="{Binding Path=. ,
Converter={StaticResource myConverter},
ConverterParameter={x:Reference entSourceValue}
}"/>
我还没有测试过这个。添加您自己的类型检查,但希望这会对您有所帮助 当我调试你的代码时,当我在模拟器中启动应用程序时,我会得到一个点击到转换器的方法。但是,当我在条目中输入某些内容,甚至没有使用Converter方法时,什么也不会发生。@LonelyDeveloper您需要引发一个属性更改事件,列表对象才能再次运行转换器。
public class SourceToTargetConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((MyObj)value).Weight * (double)((Entry)parameter).Text;
}
}