2016-02-17 87 views
1

我試圖將xaml中TextBlock的'Text'屬性綁定到全局字符串,但是當我更改字符串時,TextBlock的內容不會更改。我錯過了什麼?UWP中的數據綁定不刷新

我的XAML:

<StackPanel> 
     <Button Content="Change!" Click="Button_Click" /> 
     <TextBlock Text="{x:Bind text}" /> 
</StackPanel> 

我的C#:

string text; 
    public MainPage() 
    { 
     this.InitializeComponent(); 
     text = "This is the original text."; 
    } 

    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     text = "This is the changed text!"; 
    } 
+0

這因爲你沒有引發PropertyChanged事件將永遠不會更新。爲了更新它,創建一個將是靜態的DTO,並在其中包含字符串。靜態Dto需要實現NotifyProperty更改。 – user853710

+0

當itemsource不會刷新你可能會嘗試這個解決方案:[這裏是相關的解決方案](https://stackoverflow.com/a/47634971/2036103) –

回答

8

x:Bind的默認綁定模式是OneTime而不是OneWay,事實上這是Binding的默認設置。此外textprivate。要進行工作綁定,您需要有一個public property

<TextBlock Text="{x:Bind Text , Mode=OneWay}" /> 

而在代碼隱藏

private string _text; 
public string Text 
{ 
    get { return _text; } 
    set 
    { 
     _text = value; 
     NotifyPropertyChanged("Text"); 
    } 

加上提高的PropertyChanged在文本的制定者是很重要的。

+0

我已經更新了它,但它仍然不起作用。 –

+0

是否實施了[INotifyPropertyChanged](https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v = vs.110).aspx)? –

+0

'在文本的setter中提升PropertyChanged'你是什麼意思? –

1

爲什麼當你在後面反正代碼是你不能使用這樣的(我不知道內容只是試試看):

<TextBlock x:Name="txtSomeTextBlock/> 

public MainPage() 
{ 
    this.InitializeComponent(); 
    txtSomeTextBlock.Text = "This is the original text."; 
} 

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    txtSomeTextBlock.Text = "This is the changed text!"; 
} 
+0

這工作完美,但我想明白爲什麼與綁定版本doesn不,並且如何正確地做。 –