问题
I have a windows phone application.
Lets's say I have a CustomersViewModel class that exposes the list of customers. I have a list in xaml that binds to that list:
<ListBox ItemsSource="{Binding Path=Data}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Text="{Binding Converter={StaticResource userIdToNameConverter}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
So each item in the list box will bind to a single customer object.
CustomersViewModel has an additional property
string StoreId
In my XAML from above, I would like to pass the StoreId to the converter, in addition to the customer object that I am already passing. How can this be done elegantly?
It seems IMultiValueConverter does not exist on WP8, and it is not possible to do data binding to ConverterParameter of the converter.
回答1:
This blog post explains a work around for the problem. The idea is to create a dependency property on your converter. You can then bind your StoreId to this, instead of using the ConverterParameter.
So on your UserIdToNameConverter, you need to inherit from DependencyObject, and add the dependency property:
public class UserIdToNameConverter : DependencyObject, IValueConverter
{
public string StoreId
{
get { return (string) GetValue(StoreIdProperty); }
set { SetValue(StoreIdProperty, value); }
}
public static readonly DependencyProperty StoreIdProperty =
DependencyProperty.Register("StoreId",
typeof (string),
typeof (UserIdToNameConverter),
new PropertyMetadata(string.Empty));
public object Convert(object value, Type targetType, object parameter, string language)
{
//Your current code
//Can now use StoreId instead of ConverterParameter
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
//Same as above;
}
}
You can then bind to this dependency property within your view's resources:
<UserControl.Resources>
<UserIdToNameConverter x:Key="UserIdToNameConverter" StoreId="{Binding StoreId}"/>
</UserControl.Resources>
This is assuming your view's DataContext is set to the CustomersViewModel where it can find the StoreId property. You can then use the converter the same way as you have in your question.
As a side note, it won't work if you create the converter within the ItemTemplate instead of inside the Resources. See the blog post for more information. All credit goes to the blog's author, Sebastien Pertus.
来源:https://stackoverflow.com/questions/20229214/multivalue-converter-in-windows-phone