2014-04-04 2 views
1

WPF, MVVM 및 Entity 프레임 워크 6 코드 우선을 사용하는 첫 번째 응용 프로그램입니다. 그것은 단순한 미니 신용 시뮬레이터로, 왼쪽 패널에 신용의 매개 변수와 오른쪽 패널의 매개 변수로 이루어진 모든 변경 사항을 새로 고치는 데이터 그리드로 구성되며, 엔티티 "Echeance"컬렉션을 포함합니다. 따라서 왼쪽 패널에는 "Simulation"엔터티의 속성에 대해 데이터 바인딩 된 텍스트 상자가 포함되어 있으며 DataGrid는 ObservableCollection에 데이터 바인딩되어 있습니다.WPF 및 MVVM : 컨트롤 새로 고침 방법

문제는 매개 변수를 변경할 때 데이터 격자가 변경 내용을 새로 고치지 않는다는 것입니다.

MVVM을 사용하기 전에 응용 프로그램이 정상적으로 작동합니다.

//Entity Echeance 
public partial class Echeance : INotifyPropertyChanged 
{ 
    public long echeanceId { get; set; } 
    public byte echNumber { get; set; } 
    public double principal; 
    .... //Other fields 
    ... 
    //Navigation to the parent 

    public virtual simulation simulation { get; set; } 


//Contructor with Echeance Number 
    Echeance(byte n) 
{ 
echNumber = n; 
} 

... 


    public double MontantPrincipal 
    { 
     get 
     { 
      return principal; 
     } 

     set 
     { 
      principal = value; 
      OnPropertyChanged("MontantPrincipal"); 
     } 
    } 

...Other properties 
.... 
// 
public event PropertyChangedEventHandler PropertyChanged; 

    public void OnPropertyChanged(string propertyName) 
    { 

     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
    } 

} 



//Entity simulation 
    public partial class simulation 
{ 

     public long simulationId { get; set; } 
     ... 
     public double loyer { get; set; } 

     public virtual IList<Echeance> echeancier { get; set; } 
} 

뷰 모델은 다음과 같다 : 코드 아래

public class VMSimulation : ObservableObject 
{ 
#region Fields 
    simulation _simulation; 
    ...   
    ObservableCollection<Echeance> _echeancier; 
#endregion 


    #region Constructeur 
    public VMSimulation() 
    { 
     _simulation = new simulation(); 
     _echeancier = new ObservableCollection<Echeance>(_simulation.echeancier); 
     // LogIt(); 
    } 
    #endregion 

    #region Properties 

    public ObservableCollection<Echeance> Echeancier 
    { 
     get 
     { 
      return _echeancier; 
     } 

     set 
     { 
      _echeancier = value; 
      OnPropertyChanged("Echeancier"); 
     } 
    } 

.... 
    public double Loyer 
    { 
     get { return _simulation.loyer; } 
     set 
     { 
      _simulation.loyer = value; 
      OnPropertyChanged("Loyer"); 
     } 
    } 
... 
} 
내가

<viblend:NumberEditor x:Name="txloy"  
            Value="{Binding Path=Loyer, UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" 
            Grid.Column="7" Grid.Row="2" 
            Style="{StaticResource viBlendDecimal}" Width="72" ToolTip="Loyer computed." IsEnabled="False" /> 


<DataGrid x:Name="gridLoyers" ItemsSource="{Binding Echeancier}" 
        AutoGenerateColumns="False" 
        HorizontalAlignment="Stretch" 
        VerticalAlignment="Stretch" 
        Margin="0" 
       Grid.Column="0" Grid.Row="1" CellEditEnding="gridLoyers_CellEditEnding_1" > 
       <DataGrid.Columns> 
        <DataGridTextColumn Binding="{Binding NumLoy, Mode=TwoWay, StringFormat='{}{0:#}'}" ElementStyle="{StaticResource DataGridCellRightAlignment}"  Header="N°" /> 
        <DataGridTextColumn Binding="{Binding DateEcheance ,  StringFormat={}\{0:dd/MM/yyyy\}, Mode=TwoWay}"  ElementStyle="{StaticResource DataGridCellCenterAlignment}" Header="Echéance"/> 
        <DataGridTextColumn Binding="{Binding MontantPrincipal, StringFormat='{}{0:#.##,0}',UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"  ElementStyle="{StaticResource DataGridCellRightAlignment}" Header="Principal" /> 
        <DataGridTextColumn Binding="{Binding MontantInteret, StringFormat='{}{0:#.##,0}'}"  ElementStyle="{StaticResource DataGridCellRightAlignment}" Header="Intérêts"/> 
        <DataGridTextColumn Binding="{Binding MontantHT, StringFormat='{}{0:#.##,0}', UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"  ElementStyle="{StaticResource DataGridCellRightAlignment}" Header="Hors taxe" /> 
        <DataGridTextColumn Binding="{Binding MontantTVA, StringFormat='{}{0:#.##,0}'}"  ElementStyle="{StaticResource DataGridCellRightAlignment}" Header="TVA"/> 
        <DataGridTextColumn Binding="{Binding MontantTTC, StringFormat='{}{0:#.##,0}'}"  ElementStyle="{StaticResource DataGridCellRightAlignment}"  Header="TTC"/> 
        <DataGridTextColumn Binding="{Binding Amortfin, StringFormat='{}{0:#.##,0}'}"  ElementStyle="{StaticResource DataGridCellRightAlignment}"  Header="Amortissement"/> 
        <DataGridTextColumn Binding="{Binding Encours, StringFormat='{}{0:#.##,0}'}"   ElementStyle="{StaticResource DataGridCellRightAlignment}"  Header="Encours financier"/> 
        <DataGridCheckBoxColumn Binding="{Binding Fixe, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"   ElementStyle="{StaticResource DataGridCellRightAlignment}"  Header="Figé ?"/> 
       </DataGrid.Columns> 
      </DataGrid> 

를 새로 고침 문제가 최종적으로보기

XAML 그냥 필드 :

//Constructeur de la fenêtre 
    public simulationform() 
    { 
     InitializeComponent(); 
     VMSimulation vms = new VMSimulation(); //Instanciation du ViewModel Associé 
     this.DataContext = vms; 
     vms.ClosingRequest += (sender, e) => this.Close(); 
    } 

DataGrid가 ObservableCollection을 새로 고치지 않고 "Loyer"속성이 새로 고쳐지지 않습니다. 나는 이것을 디버깅하고 나는 "명령"이 잘 작동하고 목록에 정확한 데이터가 있지만 그것이 새로 고쳐지지 않는다는 것을 알게된다. 열 머리글을 클릭하면 DataGrid의 데이터가 올바르게 새로 고쳐집니다. 이상한 행동 !!! 재산이 아닌 필드에 값을 설정 않는 ctor에의하도록 필드 당신에게 값을 설정하여 사전

+0

... 감사합니다. 이 작업을 수행 한 것처럼 보이지만 구현이 제대로 작동하는지 확신 할 수 없습니다. – Sheridan

+0

'ItemsSource = "{Echancier, UpdateSourceTrigger = PropertyChanged} 바인딩"을 시도해보고 도움이되는지 확인하십시오. – XAMlMAX

+0

나는 그것을 시도했다. .. 아직도 같은 문제. –

답변

0

실례의 ViewModel의 명령의 코드가 없습니다.

Echeancier = new ObservableCollection<Echeance>(_simulation.echeancier); 

및 데이터 그리드 새로 고침이 잘 작동 :

public ICommand RefreshCommand 
    { 
     get 
     { 
      if (_refreshCommand == null) 
       _refreshCommand = new DelegateCommand<object>(RefreshCommandExecute); 
      return _refreshCommand; 
     } 
    } 



void RefreshCommandExecute(object obj) 
    { 
     _simulation.RefreshEcheancier(); 
     //I added this line and it works fine 
     Echeancier = new ObservableCollection<Echeance>(_simulation.echeancier); 
    } 

그래서 나는 최근에 선을 추가했다.

은 뷰 모델, 뷰 모델 *와 * 데이터 객체 클래스는`INotifyPropertyChanged` 인터페이스를 구현해야합니다에 대한 변경 사항을 업데이트하는 UI 제어를 위해

0

에서

덕분에, INotifyPropertyChange 트리거와 함께 귀하의 재산 세터를 바이 패스. 당신의 VM의 생성자가있는 경우

Codewise :

#region Constructeur 
    public VMSimulation() 
    { 
     _simulation = new simulation(); 
     Echeancier = new ObservableCollection<Echeance>(_simulation.echeancier); // instead of _echeancier = ... 
     // LogIt(); 
    } 
    #endregion 
+0

좀 더 명확하게 설명해 주시겠습니까? 당신은 아직 INotifyPropertyChanged에서 시뮬레이션을 상속해야한다는 것을 의미합니까? –

+0

Echeancier 속성 설정 도구를 우회하는 파일에 값을 설정하여 OnPropertyChanged ("Echeancier"); 호출되지 않으며 VM은 변경 사항에 대해보고 할 기회를 얻지 못합니다. – user3455395

+0

user3455395 : 나는 그것을 썼다. 위의 코드를 검토하십시오. 내가 쓴 : _echeancier = 새로운 ObservableCollection (_simulation.echeancier); Echancier가 아니라 새로운 ObservableCollection (_simulation.echeancier); –