Search code examples
wpfxamlwpf-controls

Change Parent Control propery using Child Control in WPF


I have a grid contains two TextBox's, and trying to change grid background color to red and green depends on the TextBox that get focus. However I couldn't make below snippets to work as Setter doesn't support TargetName property. Could anyone please provide a solution to achieve this in XAML

<Grid x:Name="grid">
    <StackPanel>
        <TextBox Width="300"
                 Height="40"
                 x:Name="txt1">
            <TextBox.Style>
                <Style TargetType="TextBox">
                    <Style.Triggers>
                        <Trigger Property="IsFocused"
                                 Value="True">
                            <Setter TargetName="grid"
                                    Property="Background"
                                    Value="Red" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>

        <TextBox Width="300"
                 Height="40"
                 x:Name="txt2">
            <TextBox.Style>
                <Style TargetType="TextBox">
                    <Style.Triggers>
                        <Trigger Property="IsFocused"
                                 Value="True">
                            <Setter TargetName="grid"
                                    Property="Background"
                                    Value="Green" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>
    </StackPanel>
</Grid>

Solution

  • I think one of the easiest ways is using Style.Triggers at Grid level with DataTrigger.

    <Grid x:Name="grid">
        <Grid.Style>
            <Style TargetType="{x:Type Grid}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=txt1, Path=IsFocused}" Value="True">
                        <Setter Property="Background" Value="Red" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding ElementName=txt2, Path=IsFocused}" Value="True">
                        <Setter Property="Background" Value="Green" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Grid.Style>
        <StackPanel>
            <TextBox Width="300"
                     Height="40"
                     x:Name="txt1"/>
            <TextBox Width="300"
                     Height="40"
                     x:Name="txt2"/>
        </StackPanel>
    </Grid>