[英]bound target control not updating when source changed programatically
我有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));
}
}
}
<StackPanel x:Name="myStackPanel" Orientation="Vertical">
<StackPanel.DataContext>
<local:x/>
</StackPanel.DataContext>
<TextBox Text="{Binding Text, Mode=TwoWay}" />
<TextBox Text="{Binding Text, Mode=TwoWay}"/>
</StackPanel>
上面的XAML摘錄意味着:將stackpanel的DataContext
設置為類x
的新實例。 因為通過實例進行XAML,你沒有提到的是x
的實例,直到你從StackPanel中我們得到它DataContext
。
並且,如果要測試數據綁定是否起作用,則應修改類x
現有實例(當前設置為DataContext
)。
private void Button_Click(object sender, RoutedEventArgs e)
{
var currentDataContext = (x)myStackPanel.DataContext;
x.Text = "reset success";
}
如果StackPanel
注釋中所述從代碼中設置StackPanel
的DataContext
,則將其保存以刪除XAML中的DataContext
設置部分。
您創建了一個新對象。 這就是原因。 不要僅鑄造和更改實際綁定對象的content(Text)。
當您創建新對象時,解決方案中將丟失“訂閱”。 :(
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.