将绑定中的值作为字典中的键传递

时间:2016-03-21 20:32:35

标签: c# winrt-xaml win-universal-app

我试图在xaml中使用字典制作ListViews的ListView,但我无法弄清楚如何使用。

我有一本字典:

   public Dictionary<string, float> dictionary {get;set;}

并且

    ObservableCollection<string> Parameters{get; set;}

包含所述词典中键值的名称。

我有ListView

    itemsSource = "{Binding Parameters}"

ListViews为DataTemplate,其中itemsSource类似于:

    itemsSource= "{Binding dictionary[Passed_Value]}"

我无法手动创建只包含选定值Dictionary的ListViews,因为用户可以选择显示哪些,并且有10个。

2 个答案:

答案 0 :(得分:2)

或许您只是想知道如何使用Binding访问字典。

使用此代码:

public Dictionary<string, double> Items
{
    get
    {
        var d = new Dictionary<string, double>();
        foreach (var item in Enumerable.Range(1, 10))
        {
            d.Add($"Key{item}", item);
        }
        return d;
    }
}

这个XAML:

<ListView ItemsSource="{x:Bind Items}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <Run Text="{Binding Key}" />
                <Run Text="=" />
                <Run Text="{Binding Value}" />
            </TextBlock>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

您会注意到我并没有真正使用密钥访问字典。当只通过绑定知道密钥时,无法通过密钥访问字典。也就是说,您无法将绑定传递给绑定。

以下是您可以做的事情:

<StackPanel DataContext="{Binding ElementName=ThisPage}">
    <TextBlock Text="{Binding Items[Key1]}" />
</StackPanel>

但是,当然,这要求您提前知道密钥而不是绑定它。 WinRT-XAML中没有多重绑定。

我希望这可以解决这个困惑。

答案 1 :(得分:0)

理解你的问题是一个很大的挑战。所以,我想我只是演示创建一个列表列表。从这个代码隐藏开始。

public class Level1
{
    public int Key { get; set; }
    public string Name { get; set; }
    public IEnumerable<Level2> Items { get; set; }
}

public class Level2
{
    public int Key { get; set; }
    public string Name { get; set; }
}

public IEnumerable<Level1> Items
{
    get
    {
        return Enumerable.Range(1, 10)
            .Select(x => new Level1
            {
                Key = x,
                Name = $"Level 1 Item {x}",
                Items = Enumerable.Range(1, 10)
                    .Select(y => new Level2
                    {
                        Key = y,
                        Name = $"Level 2 Item {y}",
                    })

            });
    }
}

这个XAML:

<ListView ItemsSource="{x:Bind Items}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Name}" />
                <ItemsControl ItemsSource="{Binding Items}" Margin="12,0,0,0">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <TextBlock Text="{Binding Name}" />
                            </StackPanel>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

看起来像这样:

enter image description here

请注意,我更改了嵌套的ListView并使其成为ItemsCOntrol,因为每个具有SELECTED行为的嵌套控件都会导致您真正的噩梦。除此之外,这样做。根本不确定你需要一个字典,但是绑定到字典肯定是可能的 - 只是有点笨拙。

祝你好运。