为什么在以下 silverlight 应用程序中,当我:
时在按钮处理程序中,属性InputText
仍然具有旧值“默认文本”?
我需要做些什么才能让绑定在Silverlight中运行?相同的代码在WPF中工作正常。
XAML:
<UserControl x:Class="TestUpdate123.MainPage"
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" d:DesignWidth="640" d:DesignHeight="480">
<StackPanel Margin="10" HorizontalAlignment="Left">
<TextBox
Text="{Binding InputText}"
Height="200"
Width="600"
Margin="0 0 0 10"/>
<StackPanel HorizontalAlignment="Left">
<Button Content="Convert" Click="Button_Convert_Click" Margin="0 0 0 10"/>
</StackPanel>
<TextBox
Height="200"
Width="600"
Margin="0 0 0 10"/>
<TextBlock
Text="{Binding OutputText}"/>
</StackPanel>
</UserControl>
代码背后:
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
namespace TestUpdate123
{
public partial class MainPage : UserControl, INotifyPropertyChanged
{
#region ViewModelProperty: InputText
private string _inputText;
public string InputText
{
get
{
return _inputText;
}
set
{
_inputText = value;
OnPropertyChanged("InputText");
}
}
#endregion
#region ViewModelProperty: OutputText
private string _outputText;
public string OutputText
{
get
{
return _outputText;
}
set
{
_outputText = value;
OnPropertyChanged("OutputText");
}
}
#endregion
public MainPage()
{
InitializeComponent();
DataContext = this;
InputText = "default text";
}
private void Button_Convert_Click(object sender, RoutedEventArgs e)
{
OutputText = InputText;
}
#region INotifiedProperty Block
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
答案 0 :(得分:3)
如果您在第一个文本框中明确指定了TwoWay绑定,那么它是否可以修复它?
<TextBox
Text="{Binding InputText, Mode=TwoWay}"
Height="200"
Width="600"
Margin="0 0 0 10"/>
答案 1 :(得分:0)
Text="{Binding InputText, Mode=TwoWay}"
奇怪的是它在WPF中没有明确指定Mode = TwoWay。