迭代Silverlight DataGrid

时间:2009-03-13 17:26:30

标签: silverlight silverlight-2.0

在ASP.NET中,人们发现自己经常编写如下代码:

foreach(DataListItem item in theDataList.Items){
    MyUserControl foo = item.FindControl("myUserControl") as MyUserControl;
    foo.DoSomethingNice();
}

在Silverlight中,如何迭代DataGrid(或其他集合绑定控件)的组成控件?我想将每个的不透明度设置为0.5,然后在处理时将不透明度更新为1.

使用ItemSource属性可以获得对绑定的底层IEnumerable的引用,但我想要实际的控件引用。

为了使这个更具体,假设您有这样的用户控件:

<UserControl x:Class="GridTest.TestControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="Auto" Height="25">
    <StackPanel Orientation="Horizontal">
        <TextBox Width="150" Text="{Binding FirstName}" />
        <TextBox Width="150" Text="{Binding LastName}" />
    </StackPanel>
</UserControl>

您的DataGrid模板如下所示:

<data:DataGrid x:Name="theDataGrid">
            <data:DataGrid.Columns>
                <data:DataGridTemplateColumn Header="People" Width="Auto">
                    <data:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <this:TestControl />
                        </DataTemplate>
                    </data:DataGridTemplateColumn.CellTemplate>
                </data:DataGridTemplateColumn>
            </data:DataGrid.Columns>
        </data:DataGrid>

你这样绑定:

theDataGrid.AutoGenerateColumns = false;
people = new List<Person>( 
    new Person[]{
                new Person { FirstName = "John", LastName = "Carmack" },
                new Person { FirstName = "Linus", LastName = "Torvalds" }
    }
);
theDataGrid.ItemsSource = people;

2 个答案:

答案 0 :(得分:1)

我会通过在opacity属性上使用转换器来解决您的问题。让我解释一下。

Silverlight数据绑定方法的优点在于从模型到UI的通信。这是通过使用ObservableCollection而不是List来实现更改UI的绑定列表,或者为具有更改U​​I的属性的对象实现INotifyPropertyChanged来实现的。

这使您可以避免分析和修改UI问题的代码。

基本上,您可以将需要知道的任何数据进行数据绑定以更改不透明度,并依赖转换器根据数据绑定值返回不透明度值。甜!

答案 1 :(得分:0)

也许您可以为UserControl添加'Loaded'事件,然后您可以通过这种方式获取控件引用:'TestControl testCtl = sender作为TestControl;'