wpf 动态绑定 TextBox
时间: 2024-01-21 19:04:28 浏览: 166
您好!WPF中动态绑定TextBox的方法有很多种,其中一种方法是使用数据绑定。您可以将TextBox控件与相应的变量进行绑定,做出改变变量则控件也跟着改变的效果。首先需要声明一个类,该类用来与控件绑定。以下是一个示例代码:
```csharp
public class MyTextShow : INotifyPropertyChanged
{
private string _show;
public string Show
{
get { return _show; }
set
{
_show = value;
OnPropertyChanged("Show");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
```
在XAML文件中,您可以这样绑定:
```xml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBox Text="{Binding Show, UpdateSourceTrigger=PropertyChanged}" Margin="10"/>
<Button Content="Click" Click="Button_Click"/>
</Grid>
</Window>
```
阅读全文