Search code examples
wpfuser-controlsdatatemplate

Programmatically setting the borderbrush of a border within a datatemplate in a datagrid in a usercontrol


I have a UserControl which is basically a DataGrid. The datagrid has one TemplateColumn which is bound to an object.

I want to add a property to the UserControl which will set the Borderbrush that is inside the DataTemplate.

Here is my Xaml:

 <DataGrid.Columns>
                <DataGridTemplateColumn Header="No" IsReadOnly="True">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Border x:Name="ElementBorder" BorderThickness="1">
                                <Viewbox Height="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
                                    <TextBlock Text="{Binding Name}" VerticalAlignment="Top"></TextBlock>
                                </Viewbox>
                            </Border>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>

I would like to set the ElementBorder's BorderBrush property based on a "ElementBorderColor" property in my UserControl.


Solution

  • Another solution... point your BorderBrush to a resource in your control and, in code, change the resource. Something like this:

    <SolidColorBrush x:Key="scb01"
                     Color="Red" />
    
    <DataTemplate x:Key="dt01">
      <Border x:Name="ElementBorder"
              BorderThickness="1"
              BorderBrush="{DynamicResource scb01}">
        <Viewbox Height="Auto"
                 VerticalAlignment="Stretch"
                 HorizontalAlignment="Stretch">
          <TextBlock Text="{Binding}"
                     VerticalAlignment="Top"></TextBlock>
        </Viewbox>
      </Border>
    </DataTemplate>
    

    In code:

    (Resources["scb01"] as SolidColorBrush).Color = Colors.Green;