我有这个代码。
<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”中的值。我有按钮“重置”,当他被单击时,文本框应该被清除。我怎样才能做到这一点?请帮忙:(.
您可以将 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}"/>
...