aherrick
aherrick

Reputation: 20179

Programatically Update XAML Data Template in Windows 8 App

I have a data template like so:

    <DataTemplate x:Key="itemTmpl">
        <Grid Margin="6">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

                <Border Height="90" Width="90" Background="#eee" />

            <StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="10,0,0,0">
                <TextBlock Text="{Binding Id}" Style="{StaticResource TitleTextBlockStyle}" TextWrapping="NoWrap"/>
            </StackPanel>
        </Grid>
    </DataTemplate>

I am setting a List View Item Source in the code behind like so:

lv.ItemTemplate = (DataTemplate)this.Resources["itemTmpl"];

How can I programatically change the Border Background before the template gets rendered to my UI?

Upvotes: 1

Views: 782

Answers (1)

Nate Diamond
Nate Diamond

Reputation: 5575

You can do a few things:

  • Parse the Visual Tree (using a VisualTreeHelper or extension method such as from WinRTXamlToolkit), find the border (likely by its x:Name) and set the Background.
  • Bind the Background to a value in your Item
  • Bind the Background to a value in your VM

For any of the two Bindings, you can use a Converter to convert from a non-brush value to the proper brush value (such as if you wanted it to change colors based on if it were Checked, a bool, or not).

For the second binding, make sure that you set the Source to your VM, as the DataContext will be, by default, your Item. Also, make sure that your Item inherits from INotifyPropertyChanged so that your Bindings will get updated based on the changes in data properly.

Upvotes: 1

Related Questions