views:

1438

answers:

3

In ASP.NET, one finds themselves often writing code like:

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

In Silverlight, how can one iterate through the constituent controls of a DataGrid (or other collection bound control)? I would like to set the opacity for each to something like 0.5 and then as they are processed update the opacity to 1.

Using the ItemSource property one can obtain a reference to the underlying IEnumerable that is bound, but I'd like the actual control reference.

To make this more concrete, assume you have a user control like this:

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

Your DataGrid template looks like:

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

You're binding like this:

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

I would approach your issue by using a converter on the opacity property. Let me explain.

The niceness in the silverlight approach to databinding is the communication from the model to the UI. This is accomplished by using an ObservableCollection instead of a List for binding lists that change the UI, or implementing INotifyPropertyChanged for objects with properties that change the UI.

This allows you to avoid code that analyzes and modifies UI concerns.

Basically, you would databind whatever data you need to know to alter the opacity, and rely on the converter to return the opacity value based on the databound value. Sweet!

BC
A: 

BC has it right, and it's one of the sexiest aspects of WPF/silverlight

A: 

Maybe you can add a 'Loaded' event for your UserControl, then you can get the control reference by this way: 'TestControl testCtl = sender as TestControl;'

FQL