【问题标题】:Multivalue converter in windows phonewindows phone 中的多值转换器
【发布时间】:2013-12-12 07:29:59
【问题描述】:

我有一个 Windows Phone 应用程序。

假设我有一个公开客户列表的 CustomersViewModel 类。我在 xaml 中有一个绑定到该列表的列表:

<ListBox ItemsSource="{Binding Path=Data}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Text="{Binding Converter={StaticResource userIdToNameConverter}" />                    
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

因此,列表框中的每个项目都将绑定到单个客户对象。

CustomersViewModel 有一个附加属性

string StoreId

在上面的 XAML 中,除了我已经传递的客户对象之外,我还想将 StoreId 传递给转换器。如何优雅地做到这一点?

WP8上好像没有IMultiValueConverter,无法对转换器的ConverterParameter做数据绑定。

【问题讨论】:

    标签: c# xaml data-binding windows-phone-8


    【解决方案1】:

    blog post 解释了解决该问题的方法。这个想法是在您的转换器上创建一个dependency property。然后,您可以将您的 StoreId 绑定到此,而不是使用 ConverterParameter。

    所以在你的UserIdToNameConverter上,你需要继承DependencyObject,并添加依赖属性:

    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;
        }
    }
    

    然后您可以在视图资源中绑定到此依赖属性:

    <UserControl.Resources>
        <UserIdToNameConverter x:Key="UserIdToNameConverter" StoreId="{Binding StoreId}"/>
    </UserControl.Resources>
    

    这是假设您的视图的DataContext 设置为CustomersViewModel,它可以在其中找到StoreId 属性。然后,您可以像在问题中一样使用转换器。

    附带说明,如果您在 ItemTemplate 内而不是在 Resources 内创建转换器,它将不起作用。有关更多信息,请参阅博客文章。所有功劳归于博客作者 Sebastien Pertus。

    【讨论】:

    • 如果我错了,请纠正我,但这种方法的问题似乎是你只能真正传递页面上定义的附加参数。所以我不能将多个值传递给绑定在 LLS 或列表框中的项目。
    • 我不确定我是否完全理解您的问题。如果您需要传递多个参数,则可以在转换器上添加另一个依赖项属性。或者你的意思是从你的列表框中的项目绑定转换器参数?是的,这在这里没有多大帮助,因为转换器需要在 ListBox 的 ItemTempalte 之外声明。
    • 是的,我指的是列表框中的项目,原因与您描述的完全相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多