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 ?
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</Bu开发者_StackOverflowtton>
</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; }
}
Use the inherited DataContext
of the Button:
var person = (sender as FrameworkElement).DataContext as Person;
person.Name = String.Empty;
I would suggest using a Command
instead and passing the current Person object via the CommandParameter
property. Something like this:
<Button Content="Clear"
Command="{Binding DataContext.ClearNameCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"
CommandParameter="{Binding}" />
then all you'd need to do is set the property of the object (and update the binding, since it doesn't look like Person implements INotifyPropertyChanged
)
You could use an ICommand
:
public class ClearNameCommand : ICommand
{
public bool CanExecute(object parameter, IInputElement target)
{
var person = parameter as Person;
return (person != null && person.Name.Length > 0);
}
public void Execute(object parameter, IInputElement target)
{
var person = parameter as Person;
if (person != null)
{
person.Name = String.Empty;
}
}
}
Then in the XAML:
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<TextBlock Text="{Binding Name}"></TextBlock>
<Button x:Name="btnClear"
Command="{StaticResource ClearCommand}"
CommandParameter="{Binding}">Clear</Button>
</StackPanel>
精彩评论