C# WPF 访问 DataGridTextColumn 标题内的 TextBox

问题描述 投票:0回答:1

我有这个代码。

<DataGridTextColumn Binding="{Binding nazwisko}" Header="Nazwisko" IsReadOnly="True" ElementStyle="{StaticResource verticalCenter}" FontSize="14" HeaderStyle="{StaticResource HeaderStyle}" Width="195">
<DataGridTextColumn.HeaderTemplate>
    <DataTemplate>
        <StackPanel>
            <Label VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Margin="-5,0,0,5" Content="{Binding Content, RelativeSource={RelativeSource Mode=TemplatedParent}}" Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Parent.ActualWidth}"/>
            <TextBox x:Name="txt_name" MinHeight="20" TextChanged="Filtr_TextChanged"/>
        </StackPanel>
    </DataTemplate>
</DataGridTextColumn.HeaderTemplate>
<DataGridTextColumn.CellStyle>
    <Style TargetType="DataGridCell">
        <Setter Property="Foreground" Value="{Binding FontColor}"/>
    </Style>
</DataGridTextColumn.CellStyle>

我想清除文本框“txt_name”中的值。我有按钮“重置”,当他被单击时,文本框应该被清除。我怎样才能做到这一点?请帮忙:(.

c# wpf xaml datagrid
1个回答
0
投票

您可以将 TextBox 值绑定到 祖先 DataContext。 如果您有将 ViewModel 绑定为 DataContext 的 Window:

public class MainWindowViewModel : ObservableObject
{
    private string _headerText = "InitialValue";
    public string HeaderText
    {
        get => _headerText;
        set => SetProperty(ref _headerText, value);
    }

    public IRelayCommand Reset { get; }

    public MainWindowViewModel()
    {
        Reset = new RelayCommand(OnReset);
    }

    private void OnReset()
    {
        HeaderText = string.Empty;
    }
}

然后你可以像这样使用它:

...
<DataGridTextColumn.HeaderTemplate>
    <DataTemplate>
        <StackPanel>
            <Label VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Margin="-5,0,0,5" Content="{Binding Content, RelativeSource={RelativeSource Mode=TemplatedParent}}" Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Parent.ActualWidth}"/>
            <TextBox x:Name="txt_value" Text="{Binding DataContext.HeaderText, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" MinHeight="20"/>
        </StackPanel>
    </DataTemplate>
</DataGridTextColumn.HeaderTemplate>
...
<Button Content="Reset" Command="{Binding Reset}"/>
...
© www.soinside.com 2019 - 2024. All rights reserved.