如何更正将属性绑定到文本框?
我在 mainpage.xaml 中编写这些代码
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel>
<TextBox x:Name="xxx" Text="{Binding Test}" TextChanged="xxx_TextChanged" />
<Button x:Name="click" Click="click_Click" Content="click" />
</StackPanel>
</Grid>
,在 mainpage.xaml.cs 中编写这些代码
private string test;
public string Test
{
get { return test; }
set
{
if (test != value)
{
test = value;
OnPropertyChanged("Test");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
// Constructor
public MainPage()
{
InitializeComponent();
}
private void xxx_TextChanged(object sender, TextChangedEventArgs e)
{
Debug.WriteLine(Test);
Debug.WriteLine(test);
}
,但测试未绑定到文本框,当我将 smth 写入文本框时,测试不会更改。 我做错了什么以及如何纠正?
I write these code in mainpage.xaml
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel>
<TextBox x:Name="xxx" Text="{Binding Test}" TextChanged="xxx_TextChanged" />
<Button x:Name="click" Click="click_Click" Content="click" />
</StackPanel>
</Grid>
And these in mainpage.xaml.cs
private string test;
public string Test
{
get { return test; }
set
{
if (test != value)
{
test = value;
OnPropertyChanged("Test");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
// Constructor
public MainPage()
{
InitializeComponent();
}
private void xxx_TextChanged(object sender, TextChangedEventArgs e)
{
Debug.WriteLine(Test);
Debug.WriteLine(test);
}
But Test isn't binded to textbox, when I write smth to textbox Test isn't changed.
What I doing wrong and how to correct that ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试将
BindingMode
设置为 TwoWay:我注意到的另一件事是,您的工作绑定需要设置
DataContext
,但在示例中您没有这样做。一种方法是这样的:如果首选 Xaml,您可以使用
RelativeSource
属性绑定到 Xaml 中的页面,而无需设置 DataContext:另一件事,
Test< /code> 不会在您在文本框中键入每个字符后设置,而是在用户完成编辑文本后设置,例如通过将活动控件切换到下一个。
Try setting
BindingMode
to TwoWay:The other thing I've noticed, is that your binding to work need
DataContext
to be set, but you don't do that in your example. One way to do this would be something like this:If staying in Xaml is preferred, you can use
RelativeSource
property to bind to your page in Xaml, without setting DataContext:Another thing,
Test
will be set not after every character you type in your TextBox, but after user will finish editing text, for example by switching active control to next one.