2009-05-11 6 views
2

Dans l'exemple suivant, je lier le XAML à un objet statique via ObjectDataProvider. Lorsque l'utilisateur modifie des informations, je souhaite qu'il reflète automatiquement dans le code XAML.Comment faire pour que WPF DataBinding-to-a-object fonctionne

Ce que je ne comprends pas:

  • comment puis-je l'objet perpétuer? dois-je créer un singleton? dans l'événement click, comment puis-je accéder à "l'objet en cours d'édition"
  • éventuellement je veux que les données soient récupérées à partir d'un modèle qui lit un fichier XML ou un service web, et Je veux bien sûr mon ViewModel pour vérifier mon modèle chaque seconde ou pour voir si les données ont changé et reflètent cela sur le XAML.

Comment RENDRE de ICI:

XAML:

<Window x:Class="TestBinding99382.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:TestBinding99382" 
    Title="Window1" Height="300" Width="300"> 

    <Window.Resources> 
     <ObjectDataProvider 
      x:Key="DataSourceCustomer" 
      ObjectType="{x:Type local:Customer}" MethodName="GetCustomer"/> 

     <Style x:Key="DataRowStyle" TargetType="StackPanel"> 
      <Setter Property="Orientation" Value="Horizontal"/> 
      <Setter Property="VerticalAlignment" Value="Top"/> 
      <Setter Property="Margin" Value="0 10 0 0"/> 
      <Setter Property="DataContext" 
        Value="{StaticResource DataSourceCustomer}"/> 
      <Setter Property="DockPanel.Dock" Value="Top"/> 
     </Style> 
    </Window.Resources> 

    <DockPanel> 
     <StackPanel DockPanel.Dock="Top" 
        DataContext="{StaticResource DataSourceCustomer}" 
        Orientation="Horizontal"> 
      <TextBlock Text="{Binding Path=FirstName}"/> 
      <TextBlock Text=" "/> 
      <TextBlock Text="{Binding Path=LastName}"/> 
      <TextBlock Text=" ("/> 
      <TextBlock Text="{Binding Path=FullName}" FontWeight="Bold"/> 
      <TextBlock Text=")"/> 
     </StackPanel> 

     <StackPanel Style="{StaticResource DataRowStyle}"> 
      <TextBlock Text="First Name:"/> 
      <TextBox Text="{Binding Path=FirstName}" 
         Width="200" Margin="3 0 0 0"/> 
     </StackPanel> 

     <StackPanel Style="{StaticResource DataRowStyle}"> 
      <TextBlock Text="Last Name:"/> 
      <TextBox Text="{Binding Path=LastName}" 
        Width="200" Margin="3 0 0 0"/> 
     </StackPanel> 

     <StackPanel Style="{StaticResource DataRowStyle}"> 
      <Button Content="Save Changes" Click="Button_Click"/> 
     </StackPanel> 

    </DockPanel> 
</Window> 

code Derrière:

using System.Windows; 
using System.ComponentModel; 
using System; 

namespace TestBinding99382 
{ 
    public partial class Window1 : Window 
    { 
     private Customer _customer; 

     public Window1() 
     { 
      InitializeComponent(); 
     } 

     private void Button_Click(object sender, RoutedEventArgs e) 
     { 
      //I want to edit the _customer object here 
      //and have it my changes automatically reflect in my XAML 
      //via the INotifyPropertyChanged inheritance. 
     } 
    } 

    public class Customer : INotifyPropertyChanged 
    { 
     private string _firstName; 
     private string _lastName; 

     public string FirstName 
     { 
      get 
      { 
       return _firstName; 
      } 

      set 
      { 
       _firstName = value; 
       this.RaisePropertyChanged("FirstName"); 
       this.RaisePropertyChanged("FullName"); 
      } 
     } 

     public string LastName 
     { 
      get 
      { 
       return _lastName; 
      } 

      set 
      { 
       _lastName = value; 
       this.RaisePropertyChanged("LastName"); 
       this.RaisePropertyChanged("FullName"); 
      } 

     } 

     public string FullName 
     { 
      get 
      { 
       return String.Format("{0} {1}", _firstName, _lastName); 
      } 
     } 

     public event PropertyChangedEventHandler PropertyChanged; 
     private void RaisePropertyChanged(string property) 
     { 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs(property)); 
      } 
     } 


     public static Customer GetCustomer() 
     { 
      return new Customer { FirstName = "Jim", LastName = "Smith" }; 
     } 

    } 
} 

Répondre

1

en cas de clic, comment faire J'accède au l '"objet en cours de modification"

Vous pouvez accéder à une ressource dans le code derrière en utilisant la méthode FindResource, voir ci-dessous.

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    ObjectDataProvider objectDataProvider 
     = FindResource("DataSourceCustomer") as ObjectDataProvider; 
    _customer = objectDataProvider.Data as Customer; 
} 

Pour vos questions:

Qu'est-ce que perpétuer? Vous n'êtes pas obligé de créer un singleton à la base de données dans WPF si c'est votre question.

finalement bien sûr, je veux que les données soient récupérées à partir d'un modèle qui lit un fichier XML ou un service web, et je veux bien sûr mon ViewModel pour vérifier mon modèle toutes les secondes pour voir si les données ont changé et reflète cela sur le XAML.

La liaison de données WPF met automatiquement à jour votre vue d'utilisation d'un objet INotifyPropertyChanged. Sauf pour des raisons de performances, vous ne souhaitez que mettre à jour votre vue à chaque seconde, il vous suffit de vous en tenir à une liaison de données normale.

+0

Je souhaite obtenir un exemple de travail dans lequel les données d'un modèle changent continuellement et ces modifications sont représentées en XAML. Voici un exemple que je souhaite utiliser lorsque le modèle a le DateTime en cours qui doit être reflété dans XAML: http://stackoverflow.com/questions/851595/why-is-inotifychanged-not-updating-the-variables-in-xaml –

+0

J'ai été capable de faire fonctionner cet exemple de la façon dont je voulais utiliser une méthode singleton ici: http : //stackoverflow.com/questions/852441/fat-models-skinny-viewmodels-and-dumb-views-the-best-mvvm-approach –

Questions connexes