MVVM子类属性绑定

时间:2018-11-30 18:27:53

标签: c# mvvm

我在绑定类链时遇到问题,我的listView无法刷新数据:这里

  

简化代码:

  private ObservableCollection<NewPosition> _ListPosition;
      public ObservableCollection<NewPosition> ListPosition
    {
                        get { return _ListPosition; }
                       set
                        {

                           _ListPosition = value;
                           OnPropertyChanged("ListPosition");

                        }
                    }

       public class NewPosition
               { 
              public int ID { get; set; }
               public PosStatus Status { get; set; }
                public Trade buyTrade { get; set; }
               public Trade SellTrade { get; set; }

             }

       public class Trade 
      {
                  public double DealPrice {get ; set}

      }
  

现在的视图

<ListView Grid.Row="1" Background="#FF232426" ItemsSource="{Binding 
 assetsPointCollection.ListPosition}"
     Foreground="#FFF2F3F7" Margin="0,10" FontSize="10" >
     <ListView.View>
         <GridView> 
<GridViewColumn  Header="Price" Width="80" DisplayMemberBinding="{Binding buyTrade.DealPrice}" />
     <GridViewColumn  Header="SellPrice" Width="80"
     DisplayMemberBinding="{Binding SellTrade.DealPrice}" />  
                             </GridView>
                        </ListView.View>
                    </ListView>
               </Grid>

因此,当我第一次设置Dealprice并将其添加到集合中时,它就会执行工作并显示列表值;

 NewPosition thisPos = new NewPosition();
   var trade = new Trade()
                {                   
                    DealPrice = 1000,
                 }
  thisPos.buyTrade = trade;
   ListPosition.Add(thisPos);

问题是当我想要稍后设置NewPosition.Selltrade.Dealprice时 GUI将不会显示更改(可在控制台中使用)

 pos.SellTrade = new Trade{DealPrice = 1200};

那么“实现这种代码的优雅方式是什么?

1 个答案:

答案 0 :(得分:1)

这是因为NewPosition and Trade不像您的视图模型那样实现INotifyProperyChange。窗口系统不比较对象值,而是依靠告诉它属性已更改的东西。

要获取更改,您必须删除并重新添加NewPosition,因为ObservableCollection确实会通知任何更改。

您可以查看MvvmLite寻求帮助的简单框架。

使用MvvmLite中的ObservableObject的示例,该示例为您实现了INotifyPropertyChanged:

public class NewPosition : ObservableObject
{ 
    private int _id;
    public int ID {
        get => _id;
        set => Set(ref _id, value); 
    }

    private PosStatus _status;
    public PosStatus Status {
        get => _status;
        set => Set(ref _status, value);
    }

    private Trade _buyTrade;
    public Trade buyTrade { 
        get => _buyTrade;
        set => Set(ref _buyTrade, value);
    }

    private Trade _sellTrade;
    public Trade SellTrade { 
        get => _sellTrade;
        set => Set(ref _sellTrade, value);
    }
}

public class Trade : ObservableObject
{
    private double _dealPrice;
    public double DealPrice {
        get => _dealPrice;
        set => Set(ref _dealPrice, value);
    }
}