2010-07-30 28 views
0

我有困難想這是包含在列表中的對象上使用綁定的對象,因此,例如:Silverlight的結合包含在列表

Class A 
{ 
    IList<Class B> Items; 
} 

Class B 
{ 
    string name; 
} 

我想在XAML有例如

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

那麼有什麼想法?非常感謝

+0

Ross你是姓氏嗎? – 2010-07-30 12:20:25

回答

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}"/> 

DataContext爲TextBlock的是ClassA類型的實例。

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

如果你想支持比一次性綁定的更多(這是什麼所示),你需要做的更多,比如添加INotifyPropertyChanged支持的「 B「級。