Silverlight绑定到列表中包含的对象

时间:2010-07-30 12:18:37

标签: c# wpf silverlight data-binding xaml

我很难在列表中包含的对象上使用绑定,例如:

Class A
{
    IList<Class B> Items;
}

Class B
{
    string name;
}

我希望在xaml中有例如

<Textblock Text="{Binding ClassA.Items[5].name}"/>

那么任何想法?非常感谢

2 个答案:

答案 0 :(得分:1)

为了完整起见,如果您感兴趣,这里有一个完整的工作示例。属性必须是公共的,您需要引用类的实例,而不是类名。

这适用于SL4 +。

<UserControl x:Class="TestSilverlightStuff.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestSilverlightStuff"            
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<UserControl.Resources>
    <local:A x:Key="AData" />        
</UserControl.Resources>    
<Grid x:Name="LayoutRoot" Background="White"  >        
    <TextBlock 
               HorizontalAlignment="Left" 
               Text="{Binding Items[2].Name, Source={StaticResource AData}" 
               />
</Grid>
</UserControl>

和C#:

using System.Collections.Generic;
using System.Windows.Controls;

namespace TestSilverlightStuff
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }

    public class A
    {        
        public A()
        {
            Items = new List<B>();
            Items.Add(new B() { Name = "WiredPrairie" });
            Items.Add(new B() { Name = "Microsoft" });
            Items.Add(new B() { Name = "Silverlight" });
            Items.Add(new B() { Name = ".NET" });
            Items.Add(new B() { Name = "Windows" });
            Items.Add(new B() { Name = "Overflow" });
        }

        public IList<B> Items 
        { 
            get; private set; 
        }
    }

    public class B
    {
        public string Name { get; set; }
    }
}

如果您想支持多个一次性绑定(显示的内容),您需要执行更多操作,例如向“B”类添加INotifyPropertyChanged支持。

答案 1 :(得分:0)

在属性路径中使用索引器,但路径的每个步骤都必须是属性。此外,每个步骤都需要具有公共辅助功能。尝试更改为: -

public class ClassA   
{   
    public IList<ClassB> Items {get; set;}   
}   

public class ClassB   
{   
    public string Name {get; set;}   
}

的Xaml: -

<Textblock Text="{Binding Items[5].Name}"/>  

TextBlock的DataContextClassA类型的实例。