Search code examples
c#wpfdatagridtemplatecolumnvisual-tree

Clear TextBlock from Button when they both are in a DataGridTemplateColumn


I have a DataGrid with DataGridTemplateColumn. The DataGridTemplateColumn contains a button and TextBlock. I want that pressing the button will clear the textBlock's text. How do I do that ?

enter image description here

XAML:

 <Grid>
    <DataGrid ItemsSource="{Binding Persons}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}">
            </DataGridTextColumn>
            <DataGridTemplateColumn Header="Mask Expiration Time">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
                            <TextBlock Text="{Binding Name}"></TextBlock>
                            <Button Name="btnClear" Click="btnClear_Click" >Clear</Button>
                        </StackPanel>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

CS code:

 public partial class MainWindow : Window
{
    public List<Person> Persons { get; set; }

    public MainWindow()
    {
        Persons = new List<Person> { new Person { Name = "James" }, new Person { Name = "Kate" } };
        DataContext = this;
        InitializeComponent();
    }

    private void btnClear_Click(object sender, RoutedEventArgs e) {
        var clearbutton = (Button) sender;

        // clear the Name
    }
}

public class Person
{
    public string Name { get; set; }
}

Solution

  • Use the inherited DataContext of the Button:

    var person = (sender as FrameworkElement).DataContext as Person;
    person.Name = String.Empty;