首页 > 解决方案 > WPF 绑定到以哈希键为索引的可观察集合

问题描述

以下代码:

    <UserControl x:Class="MyProgram.Views.MyControlContainer"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:MyProgram.Views"
             xmlns:common_model="clr-namespace:MyProgram.Models;assembly=CommonTitan"
             mc:Ignorable="d" 
            >
    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <local:MyControl x:Name="MyControl1" DataContext="{Binding MyControlCollection[8]}" Grid.Row="0" Grid.Column="0"/>
        <local:MyControl x:Name="MyControl2" DataContext="{Binding MyControlCollection[9]}" Grid.Row="0" Grid.Column="1"/>
        <local:MyControl x:Name="MyControl3" DataContext="{Binding MyControlCollection[10]}" Grid.Row="0" Grid.Column="2"/>                   
    </Grid>
</UserControl>

适当地(据我所知)将我绑定到我在集合中指定的项目。在实际使用中,它将使用一个可观察的字典,这些索引是我无法提交代码的哈希值。是否可以将 2 个已知参数传递给某种转换器以获取哈希?或者甚至将 2 个值传递给转换器,最终将项目从可观察字典中返回?

标签: wpfdata-bindingobservablecollection

解决方案


您可以传递 2 个已知值作为转换器参数,例如:

<local:MyControl x:Name="MyControl1" DataContext="{Binding MyControlCollection, Converter={StaticResource CollectionConverter}, ConverterParameters='8.9'}" />

在您的转换器类中,您可以在此处使用它,将参数解析为字符串:

public class CollectionConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (parameter != null)
        {
            string[] param = (parameter as string).split('.');
            if (int.Parse(param[0]) == 8)
               return (value as ObservableCollection)[8];
            else
               return (value as ObservableCollection)[0];
        }
        return null;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new InvalidOperationException("cannot cast the value");
    }
}

推荐阅读