我有2個「文本框」綁定到源模式爲「mode = 2way」的源字符串屬性。當我改變一個文本,另一個完全改變。但是,當我以編程方式更改源字符串既不會得到更新。我無法弄清楚我錯過了什麼。這裏是我的代碼片段:當編寫程序源改變時綁定的目標控件不更新
XAML代碼:
<StackPanel Orientation="Vertical">
<StackPanel.DataContext>
<local:x/>
</StackPanel.DataContext>
<TextBox Text="{Binding Text,Mode=TwoWay}" />
<TextBox Text="{Binding Text, Mode=TwoWay}"/>
</StackPanel>
<Button Content="Reset" Click="Button_Click"/>
按鈕單擊處理程序:
private void Button_Click(object sender, RoutedEventArgs e)
{
obj = new x() { Text="reset success"};
}
對象類:
class x:INotifyPropertyChanged
{
private string text;
public string Text
{
get { return text; }
set
{
text = value;
OnPropertyChange("Text");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChange(string propertyName)
{
PropertyChangedEventHandler propertyChangedEvent = PropertyChanged;
if (propertyChangedEvent != null)
{
propertyChangedEvent(this, new PropertyChangedEventArgs(propertyName));
}
}
}
我找到了一種解決方法,通過在代碼 – Sidney
中設置stackpanel的datacontext請檢查答案或給我們添加更多的幫助 – Krekkon