【问题标题】:Silverlight 4: how to setup properties of the control in custom listSilverlight 4:如何在自定义列表中设置控件的属性
【发布时间】:2010-08-23 03:52:34
【问题描述】:

我有一个对象列表,并希望将其绑定到自定义控件列表以进行显示。

XAML 代码:

                <Pages:MyItemsControl ItemsSource="{Binding SquadFieldPlayers}">
                    <Pages:MyItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <Canvas Height="180" Width="169" />
                        </ItemsPanelTemplate>
                    </Pages:MyItemsControl.ItemsPanel>
                    <Pages:MyItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Pages:FieldItem />
                        </DataTemplate>
                    </Pages:MyItemsControl.ItemTemplate>
                </Pages:MyItemsControl >

“MyItemsContol”的源代码:

    public class MyItemsControl : ItemsControl
{
    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
    {
        FrameworkElement contentitem = element as FrameworkElement;
        if (contentitem != null)
        {
            Binding leftBinding = new Binding("PositionX");
            Binding topBinding = new Binding("PositionY");
            contentitem.SetBinding(Canvas.LeftProperty, leftBinding);
            contentitem.SetBinding(Canvas.TopProperty, topBinding);
            base.PrepareContainerForItemOverride(element, item);             
        }
    }
}

在另一个话题。在这里,我将对象的位置属性绑定到 Left 和 Top 属性(显示在画布上的适当位置)。

问题1:如何设置FieldItem控件的另一个属性(我里面有textBlock并希望他显示来自数据对象的其他数据项)?

这是我的 FieldItem 控件:

<UserControl x:Class="VfmElitaSilverlightClientView.Pages.FieldItem" ...>    
<Grid Height="16" Width="16">
    <Ellipse Fill="Yellow" Height="16" Width="16">
    </Ellipse>
    <TextBlock Name="TeamNumberTextBlock" Text="22" TextAlignment="Center" FontStyle="Italic" />
</Grid>

我想用有意义的数据填充 TeamNuberTextBlock。

问题2:为什么FieldItem的DataContext对象没有设置为我的数据对象?

谢谢!

【问题讨论】:

    标签: silverlight data-binding binding silverlight-4.0


    【解决方案1】:

    我不知道它是如何工作的,但是要将我的控件绑定到数据对象实际上不需要任何东西。属性映射是通过通常的绑定完成的:

    <UserControl x:Class="VfmElitaSilverlightClientView.Pages.FieldItem" ...>    
    <Grid Height="16" Width="16">
        <Ellipse Fill="Yellow" Height="16" Width="16">
        </Ellipse>
        <TextBlock Name="TeamNumberTextBlock" Text="**{Binding TeamNumber}**"
                   TextAlignment="Center" FontStyle="Italic" />
    </Grid>
    

    我将不胜感激。提前感谢您的努力!

    【讨论】:

    • 说明:最初我希望在“MyCustomList”类的“PrepareContainerForItemOverride”方法中设置要控制的数据对象绑定。但实际上这是稍后完成的,并且通常的绑定适用于这种情况。
    猜你喜欢
    • 2011-08-26
    • 2011-03-20
    • 1970-01-01
    • 2011-02-16
    • 2019-01-17
    • 2010-12-26
    • 2011-04-09
    • 1970-01-01
    • 2012-09-09
    相关资源
    最近更新 更多