2015-07-19 67 views
0

我遇到了更新文本框中的文本問題。我得到這個主窗口:C#WPF更新屬性更改文本框

<Window x:Class="TestDatabinding.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525"> 
<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition/> 
     <RowDefinition/> 
     <RowDefinition/> 
    </Grid.RowDefinitions> 
    <TextBox Grid.Row="0" Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10,10,10,10"/> 
    <Button Grid.Row="1" Content="Click me" Margin="10,10,10,10" Click="Button_Click"></Button> 
    <Button Grid.Row="2" x:Name="a1" Content="ShowText" Margin="10,10,10,10" Click="a1_Click" ></Button> 
</Grid> 

現在CS-文件中查找該主窗口的樣子:

using System.Windows; 
namespace TestDatabinding 
{ 
    public partial class MainWindow : Window 
    { 
     MainWindowViewModel mwvm; 
     public MainWindow() 
     { 
      InitializeComponent(); 
      mwvm = new MainWindowViewModel(); 
      this.DataContext = mwvm; 
     } 
     private void Button_Click(object sender, RoutedEventArgs e) 
     { 
      mwvm.ChangeText(); 
      this.DataContext = mwvm; 
     } 
     private void a1_Click(object sender, RoutedEventArgs e) 
     { 
      mwvm.showText(); 
     } 
    } 
} 

最後但並非最不重要的ViewModel類:

using System.ComponentModel; 
using System.Windows; 
namespace TestDatabinding 
{ 
    class MainWindowViewModel 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 
     private string text; 
     public string Text 
     { 
      get { return this.text; } 
      set 
      { 
       this.text = value; 
       OnPropertyChanged("Text"); 
      } 
     } 
     protected void OnPropertyChanged(string name) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) 
      { 
        handler(this, new PropertyChangedEventArgs(name)); 
      } 
     } 
     public void ChangeText() 
     { 
      this.Text = "Hey paadddyy"; 
     } 
     public void showText() 
     { 
      MessageBox.Show(Text); 
     } 
    } 
} 

我沒有實現ICommands,因爲這是一個簡單的測試。 現在按鈕的工作正常,但文本框文本沒有得到更新。 任何建議我可以做什麼?當我點擊第一個按鈕時,我只想顯示「Hey paadddyy」。我按下第二個按鈕,然後第一個消息框顯示「嘿paadddyy」,但文本框的文本仍然不會更新:(

感謝您爲每個提示後;)

回答

2

MainWindowViewModel沒有實現INotifyPropertyChanged。它需要看起來像:

class MainWindowViewModel: INotifyPropertyChanged 

您定義的事件,但沒有實現接口

0

它需要實現INotifyPropertyChanged的

我建議,如果你想要做的與通知事屬性。另一個簡單的方法是將Caliburn.Micro Framework應用於您的項目。

Follow this link.