当Button都位于DataGridTemplateColumn中时,从Button中清除TextBlock

时间:2011-05-23 16:26:23

标签: c# wpf datagridtemplatecolumn visual-tree

我有一个带DataGridTemplateColumn的DataGrid。 DataGridTemplateColumn包含一个按钮和TextBlock。 我想按下按钮将清除textBlock的文本。 我该怎么做?

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代码:

 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; }
}

3 个答案:

答案 0 :(得分:2)

我建议使用Command代替并通过CommandParameter属性传递当前的Person对象。像这样:

<Button Content="Clear" 
        Command="{Binding DataContext.ClearNameCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" 
        CommandParameter="{Binding}" />

然后您需要做的就是设置对象的属性(并更新绑定,因为它看起来不像Person实现INotifyPropertyChanged

答案 1 :(得分:2)

使用Button的继承DataContext

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

答案 2 :(得分:1)

您可以使用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;
        }
    }
}

然后在XAML中:

<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
    <TextBlock Text="{Binding Name}"></TextBlock>
    <Button x:Name="btnClear"
            Command="{StaticResource ClearCommand}"
            CommandParameter="{Binding}">Clear</Button>
</StackPanel>