2014-11-16 4 views
1

Так что проблема в том, что независимо от того, что я меняю текст в своем текстовом поле, это не изменяет свойство в коде, хотя я его связываю. Я использую MVVM шаблон так: My Model:WPF Binding не обновляет данные

public class Shipment 
{ 
    public Shipment() {} 

    public int ShipmentId {get;set;} 

    //LP and Payer 
    [Required] 
    public long ExternalNumber {get ; set;} 
    public long MPKNumber { get; set; } 
    public long ContractNumber { get; set; } 
    public Payer Payer { get; set; } 
    public Payment Payment { get; set; } 
    //And much more but i'm working on these right now 
} 

Мой ViewModel:

public class PrepareNewViewModel : INotifyPropertyChanged 
{ 
    private Shipment shipment { get; set; } 

    public Shipment Shipment 
    { 
     get 
     { 
      return shipment; 
     } 
     set 
     { 
      if (shipment != value) 
      { 
       shipment = value; 
       RaisePropertyChanged("Shipment"); 
      } 
     } 
    } 

    public PrepareNewViewModel() 
    { 
     Shipment = new Shipment(); 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    private void RaisePropertyChanged(string propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 

И мой Вид:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:Controls ="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit" 
     xmlns:Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" 
     x:Class="SmartShipping.Views.Pages.PrepeareNew" 
     xmlns:local ="clr-namespace:SmartShipping.ViewModels" 
     xmlns:System="clr-namespace:System;assembly=mscorlib" 
     xmlns:Model ="clr-namespace:SmartShipping.Model" 
     mc:Ignorable="d" 
     d:DesignHeight="889" d:DesignWidth="959" 
     Title="PrepeareNew"> 

    <Page.DataContext> 
     <local:PrepareNewViewModel/> 
    </Page.DataContext> 

    <Page.Resources> 
     <ObjectDataProvider x:Key="dataFromEnumPayer" MethodName="GetValues" ObjectType="{x:Type System:Enum}"> 
      <ObjectDataProvider.MethodParameters> 
       <x:Type TypeName="Model:Payer"/> 
      </ObjectDataProvider.MethodParameters> 
     </ObjectDataProvider> 

     <ObjectDataProvider x:Key="dataFromEnumPayment" MethodName="GetValues" ObjectType="{x:Type System:Enum}"> 
      <ObjectDataProvider.MethodParameters> 
       <x:Type TypeName="Model:Payment"/> 
      </ObjectDataProvider.MethodParameters> 
     </ObjectDataProvider> 
    </Page.Resources> 

    <GroupBox Header="LIST PRZEWOZOWY I PŁATNIK" HorizontalAlignment="Left" 
       VerticalAlignment="Top" Margin="10,131,0,0" Height="146" Width="458"> 
     <Grid HorizontalAlignment="Left" Width="448" Margin="0,0,-2,0"> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="28*"/> 
       <ColumnDefinition Width="28*"/> 
       <ColumnDefinition Width="56*"/> 
      </Grid.ColumnDefinitions> 

      <Label Content="Nr zewnętrzny:" HorizontalAlignment="Left" 
        VerticalAlignment="Top" Margin="10,8,0,0" Width="138" Grid.ColumnSpan="2"/> 
      <TextBox Height="24" Margin="10,31,10,0" TextWrapping="Wrap" 
        Text="{Binding Shipment.ExternalNumber, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" 
        VerticalAlignment="Top" Grid.ColumnSpan="2"/> 

      <Label Content="Nr MPK:" HorizontalAlignment="Left" VerticalAlignment="Top" 
        Margin="0,10,0,0" Grid.Column="2" Width="73"/> 
      <TextBox Height="24" Margin="0,31,10,0" TextWrapping="Wrap" 
        Text="{Binding Shipment.MPKNumber, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" 
        VerticalAlignment="Top" Grid.Column="2" 
        Background="{DynamicResource {x:Static SystemColors.ControlLightLightBrushKey}}"/> 

      <Label Content="Płatnik usługi:" HorizontalAlignment="Left" 
        VerticalAlignment="Top" Margin="10,69,0,0"/> 
      <ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnumPayer}}" 
         Margin="10,92,0,0" VerticalAlignment="Top" Height="24" 
         Background="{DynamicResource {x:Static SystemColors.ControlLightLightBrushKey}}"/> 

      <Label Content="Forma płatności:" HorizontalAlignment="Left" 
        VerticalAlignment="Top" Margin="5,69,0,0" Grid.Column="1"/> 
      <ComboBox SelectedItem="{Binding Shipment.Payment}" 
         ItemsSource="{Binding Source={StaticResource dataFromEnumPayment}}" 
         Margin="10,92,10,0" VerticalAlignment="Top" Height="24" 
         Background="{DynamicResource {x:Static SystemColors.ControlLightLightBrushKey}}" 
         Grid.Column="1"/> 

      <Label Content="Nr umowy:" HorizontalAlignment="Left" 
        VerticalAlignment="Top" Margin="0,66,0,0" Grid.Column="2"/> 
      <TextBox HorizontalAlignment="Left" Height="24" 
        Margin="0,92,0,0" TextWrapping="Wrap" 
        VerticalAlignment="Top" Width="214" Grid.Column="2" 
        Text="{Binding Shipment.ContractNumber, ValidatesOnDataErrors=True}"/> 
     </Grid> 
    </GroupBox> 
</Page> 

Может быть, я не связывают каждое свойство модели?

+0

Изменено ли ваше свойство Shipment.ExternalNumber публичного свойства при изменении свойства? – overloading

+0

Нет, но, как вы видите, все свойство Shipment имеет. Я попытаюсь добавить его и посмотреть, помогает ли это – SebOlens

+0

Включите расширенную трассировку и отладку. diag: PresentationTraceSources.TraceLevel = «Высокий». Он должен показывать любые ошибки привязки. – Paparazzi

ответ

1

Хорошее эмпирическое правило для MVVM заключается в том, что ViewModel и View имеют отношение 1 к 1. Это имело бы больше смысла для меня, если бы у вас были свойства для каждого члена Отгрузки. В противном случае члены Shipment не будут обновлены. Хотя интуитивно Shipment технически меняется, свойства обновляются только тогда, когда вы обновляете их ценность, а не их членов.

Ваши текстовые поля технически связаны только одним способом. Когда вы меняете их, члены Отгрузки не обновляются. Мне было любопытно, если бы это было возможно, поэтому я сам тестировал его в проекте, над которым я работаю, и, конечно же, изменение членов моей модели не вызвало RaisePropertyChanged.

Смежные вопросы