我有一个静态的字符串集合,并希望从某个索引中显示其中一个字符串。该索引在运行时提供,并且是另一个集合中第二个索引中的整数值。
我可以绑定到静态集合,但是如何将路径绑定到另一个的值 采集? 也就是说,我将什么用作TextBlock绑定中Path参数的值?
这里的代码仅用于实验,不是工作代码的一部分。它是Visual Studio Designer友好的,如果我得到正确的绑定,它将在设计师周三显示而不运行:
<Window x:Class="BindingCollectionIndex.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BindingCollectionIndex"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:AnotherClass
x:Key="Foo" />
</Window.Resources>
<Grid>
<TextBlock
Text="{Binding Source={x:Static local:MyStaticCollections.Days},
Path=[**Wrong ... Foo.CollectionOfIntegers[2]**]}" />
</Grid>
静态类:
using System.Collections.Generic;
namespace BindingCollectionIndex
{
static class MyStaticCollections
{
public static List<string> Days =new List<string> { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
}
}
提供索引值的类:
using System.Collections.ObjectModel;
namespace BindingCollectionIndex
{
class AnotherClass
{
private ObservableCollection<int> collectionOfIntegers = new ObservableCollection<int>
{
1,2,3,4,5
};
public ObservableCollection<int> CollectionOfIntegers
{
get
{
return collectionOfIntegers;
}
}
}
}
后面的xaml代码中没有添加任何内容。
感谢阅读。 大卫
答案 0 :(得分:0)
你考虑过使用字典吗?
class DaysViewModel
{
public IDictionary<int,string> Days { get; set; }
public DaysViewModel()
{
Days = new Dictionary<int, string>
{
{1,"Monday"},
{2,"Tuesday"},
{3,"Wednesday"},
{4,"Thursday"},
{5,"Friday"}
};
}
}
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:DaysViewModel x:Key="Week" />
</Window.Resources>
<Grid>
<TextBox Text="{Binding Source={StaticResource Week},Path=Days[2]}" />
</Grid>