Ui在代码隐藏中更新属性时不更新

时间:2017-10-14 10:47:38

标签: wpf mvvm binding

当我在代码Behind中更改属性时,我想更新我的datagrid单元格。我的代码是     模型(实体)

public partial class IGdaily
{
    public int GDaily_Id { get; set; }
    public int Item_Id { get; set; }
}

查看模型

  public class Vm_Purchase : INotifyPropertyChanged
{
    IGoldEntities db = new IGoldEntities();
    //public ObservableCollection<IGdaily> Vm_IGdaily { get; set; }

    public IGdaily Obj_IGdaily { get; set; }
    public Vm_Purchase()
    {
        Obj_IGdaily = new IGdaily();
    }
    public Int32 Item_Id
    {
        get { return Obj_IGdaily.Item_Id; }
        set
        {
            Obj_IGdaily.Item_Id = value;
            NotifyPropertyChanged("Item_Id");
        }
    }
public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] string PropertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
        }
    }
 }

在Xaml

 <iG:DataGridTextcolumn Binding="{Binding Item_Id, Mode=OneWay}" Header="Item Id" Width="SizeToHeader"  />

在主窗口中

 Vm_Purchase ItmId = new Vm_Purchase();
 ItmId.Item_Id = Id;

这里我想在代码中更改Id,我的问题是网格单元格没有更新。请帮我解决我的问题。我可以使用ObservableCollection来实现这一点。 谢谢

1 个答案:

答案 0 :(得分:0)

给定的代码不完整,我无法弄清问题是什么。什么是DataGrid控件的ItemsSource?它是如何绑定到DataGrid控件的?

您可能正在寻找以下代码:

public partial class IGdaily : INotifyPropertyChanged
{
    private int _gDailyId;
    private int _itemId;

    public int GDaily_Id
    {
        get { return _gDailyId; }
        set
        {
            _gDailyId = value;
            NotifyPropertyChanged();
        }
    }

    public int Item_Id
    {
        get { return _itemId; }
        set
        {
            _itemId = value;
            NotifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] string PropertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
        }
    }
}

在主窗口中

public partial class MainWindow : Window
{
    public ObservableCollection<IGdaily> Vm_IGdaily { get; } = new ObservableCollection<IGdaily>();
    private IGdaily testData = new IGdaily();

    public MainWindow()
    {
        InitializeComponent();

        TheDataGridControl.ItemsSource = Vm_IGdaily;
        Vm_IGdaily.Add(testData);
    }

    private void Button1_OnClick(object sender, RoutedEventArgs e)
    {
        testData.GDaily_Id = 100;
    }
}