我是WPF概念的新手。我想在文本框中显示一个字符串。我尝试了以下C#代码和XAML将字符串绑定到TextBox.Text属性。
C#代码:
public partial class Window1 : Window
{
public int TmpVal;
public string TmpStr;
public Window1()
{
TmpVal = 50;
TmpStr = "Windows Created";
InitializeComponent();
this.DataContext = this;
}
private void viewButton_Click(object sender, RoutedEventArgs args)
{
TmpStr = "Button clicked";
}
}
}
XAML:
<Window x:Class="TestWPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="600" Width="800" x:Name="ThisWindow">
<Grid>
<TextBox Name="txtTest1" Margin="200,0,200,200" HorizontalAlignment="Left" Height="50" Width="200" Text="{Binding TmpStr, ElementName=ThisWindow}" />
<Button Name="butTest1" Click="viewButton_Click">Test123</Button>
</Grid>
</Window>
执行时,我的文本框中总是会出现空白文本(即使我调用了click事件)。
我浏览了stackoverflow网站,但无法解决问题(虽然很多问题都接近这个问题)
如果有人被忽视或遗漏,有人可以建议我吗?
答案 0 :(得分:5)
数据绑定不适用于字段。改为使用属性:
public int TmpVal {get; set;}
public string TmpStr {get; set;}
此外,如果您希望文本框自动从数据中获取更改,您理想情况下需要实现INotifyPropertyChanged或使其成为依赖项属性或为每个XXX属性设置XXXChanged事件(这不再起作用了)。
<Window x:Class="WpfApplication5.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" x:Name="ThisWindow">
<StackPanel>
<TextBox Name="txtTest1" Text="{Binding TmpStr, ElementName=ThisWindow}" />
<Button Name="butTest1" Click="viewButton_Click">Test123</Button>
</StackPanel>
</Window>
背后的代码:
public partial class Window1 : Window, INotifyPropertyChanged
{
public Window1()
{
this.TmpStr = "Windows Created";
this.InitializeComponent();
this.DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
public string TmpStr { get; set; }
public int TmpVal { get; set; }
private void viewButton_Click(object sender, RoutedEventArgs args)
{
this.TmpStr = "Button clicked";
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("TmpStr"));
}
}
}