2016-03-25 15 views
1

私はバインディングの概念を初めて習得しており、次のことに固執しています。依存関係のプロパティがUIを更新しない

public sealed partial class MainPage : Page 
{ 
    Model model; 

    public MainPage() 
    { 
     this.InitializeComponent(); 

     model = new Model(); 

     this.DataContext = model; 
    } 

    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     model.Name = "My New Name"; 
    } 
} 

class Model : DependencyObject 
{ 
    public static DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Model), new PropertyMetadata("My Name")); 

    public string Name 
    { 
     get { return (string)GetValue(NameProperty); } 
     set { SetValue(NameProperty, value); } 
    }  
} 

TextプロパティのTextプロパティにNameプロパティをバインドしました。私がする必要があるのは、ボタン上で、テキストボックスの値を更新する必要がある名前の値を更新したいと思うだけです。私は、通常のCLRプロパティの代わりに依存プロパティを使用すると、INotifyPropertyChangedを実装する必要はありません。

ただし、UIの値が期待通りに更新されません。何か不足していますか?

ありがとうございます。

+0

XAMLを表示しますか? – Euphoric

+0

WPFのTextViewなどのコントロールはありません。どのようなコントロールですか? – Euphoric

+0

これはwpfではないWindowsのメトロアプリです。 –

答えて

0

あなたの質問に対処する必要があることがいくつかあります。まず第一に、あなたのモデルがDependencyObjectから継承する必要はありません、むしろそれはINotifyPropertyChangedのを実装する必要があります。

public class Model : INotifyPropertyChanged 
{ 
    string _name; 
    public string Name 
    { 
     get { return _name; } 
     set 
     { 
      if (_name != value) 
      { 
       NotifyPropertyChanged("Name"); 
      } 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
    public void NotifyPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

INotifyPropertyは、あなたのページ/ウィンドウ/オブジェクト内のDependencyPropertyとして使用することができます実装するオブジェクト:

public static readonly DependencyProperty ModelProperty = DependencyProperty.Register("Model", 
     typeof(Model), typeof(MainWindow)); 

    public Model Model 
    { 
     get { return (Model)GetValue(ModelProperty); } 
     set { SetValue(ModelProperty, value); } 
    } 

最後に、そして、あなたはXAMLのものにあなたのTextBox.Textプロパティをバインドすることができます。

<Grid> 
    <StackPanel Orientation="Vertical"> 
     <TextBox Text="{Binding Name}"/> 
     <Button Click="Button_Click">Click</Button> 
    </StackPanel> 
</Grid> 

INotifyPropertyChangedのはまだ必要hでありますモデルオブジェクトが更新されたことをUIが知る方法が必要であるためです。

関連する問題