簡體   English   中英

Silverlight綁定到列表中包含的對象

[英]Silverlight binding to an object contained in a list

我試圖在列表中包含的對象上使用綁定很困難,例如:

Class A
{
    IList<Class B> Items;
}

Class B
{
    string name;
}

我想例如在xaml中

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

有什么想法嗎? 非常感激

為了完整起見,如果您有興趣,這里是一個完整的工作示例。 屬性必須是公共的,並且您需要引用類的實例,而不是類名。

這適用於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”類。

在屬性路徑中使用索引器,但路徑的每個步驟都必須是屬性 同樣,每個步驟都需要具有公共可訪問性。 嘗試更改為:-

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類型的實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM