【问题标题】:WPF MVVM GridView binding of cell values to ViewModel propertiesWPF MVVM GridView 将单元​​格值绑定到 ViewModel 属性
【发布时间】:2019-02-28 04:05:49
【问题描述】:

MVVM 新手正在寻找有关数据网格绑定的一些指导。我很难设置我可以看到数据网格单元格的内容已更改的属性。我一开始很简单,我试图用货币代码设置一个可更新的国家列表。有没有办法可以将我的网格列单元格绑定到视图模型中的属性?到目前为止,我刚刚介绍了 CurrencyCode 的属性,但我从未执行过 setter。我究竟做错了什么?

型号:

using System.Linq;

使用 System.Collections.ObjectModel;

命名空间 AdminTool.DataModel.Repositories { 公共类 AccountingRepository : BaseRepository { 私有 AdminToolEntities 实体 = new AdminToolEntities();

    // Country List

    public ObservableCollection<CountryData> GetCountryList()
    {
        var result = (from c in entities.Countries
                      from u in entities.Currencies.Where(u => u.ID == c.CurrencyID).DefaultIfEmpty()
                      select new CountryData { IsChanged = false,
                                               ID = c.ID,
                                               CountryName = c.CountryName,
                                               CountryCodeISO = c.CountryCodeISO,
                                               CurrencyCode = u.CurrencyCode})
                      .OrderBy(o => o.CountryName)
                      .ToList();
        return new ObservableCollection<CountryData>(result);
    }

    public void SaveCountryList(ObservableCollection<CountryData> countryList)
    {

        var result = (from l in countryList
                      from c in entities.Countries.Where(c => c.ID == l.ID)
                      from u in entities.Currencies.Where(u => u.CurrencyCode == l.CurrencyCode).DefaultIfEmpty()
                      where l.IsChanged
                      select l)
                      .ToList();
        foreach (CountryData cd in result)
        {
            Country c = (Country)entities.Countries.Where(l => l.ID == cd.ID).FirstOrDefault();
            if (c == null) // new entry
            {
                c = new Country();
                entities.Countries.Add(c);
            }
            c.CountryName = cd.CountryName;
            c.CountryCodeISO = cd.CountryCodeISO;
            c.Currency = entities.Currencies.Where(u => u.CurrencyCode == cd.CurrencyCode).FirstOrDefault();
        }
        entities.SaveChanges();
    }
}

/// <summary>
/// Data structures
/// </summary>
public class CountryData
{
    public int ID { get; set; }
    public string CountryName { get; set; }
    public string CountryCodeISO { get; set; }
    public string CurrencyCode { get; set; }
    public bool IsChanged { get; set; }
}

}

查看:

<Window x:Class="AdminTool.Desktop.View.CountryList"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:vm="clr-namespace:AdminTool.Desktop.ViewModel"
    Title="AdminTool" Height="600" Width="500">
<Window.DataContext>
    <vm:AccountingViewModel/>
</Window.DataContext>
<Grid>
    <DataGrid Name="dgCountryList" 
              ItemsSource="{Binding CountryList, Mode=TwoWay}"
              SelectedItem="{Binding Path=SelectedCountry, Mode=TwoWay}"
              HorizontalAlignment="Left" VerticalAlignment="Top" Height="450" Width="450" Margin="20,20,0,0"
              AutoGenerateColumns="False"
              SelectionMode="Single"
              SelectionUnit="FullRow"
              GridLinesVisibility="All"
              CanUserDeleteRows="True"
              CanUserAddRows="True">
        <DataGrid.RowStyle>
            <Style TargetType="{x:Type DataGridRow}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=IsChanged}" Value="true" >
                        <Setter Property="Background" Value="LightGreen" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.RowStyle>
        <DataGrid.Columns>
            <!--<DataGridTextColumn Header="ID" Binding="{Binding ID}" Width="50" />-->
            <DataGridTextColumn Header="Country" Binding="{Binding Path=CountryName, Mode=TwoWay}" Width="250" />
            <DataGridTextColumn Header="ISO Code" Binding="{Binding Path=CountryCodeISO, Mode=TwoWay}" Width="80" />
            <DataGridTextColumn Header="Currency" Binding="{Binding Path=CurrencyCode, Mode=TwoWay}" Width="80" />
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Save" Command="{Binding Path=SaveCommand}" IsEnabled="{Binding Path=UpdateButtonEnabled}" HorizontalAlignment="Left" Margin="223,512,0,0" VerticalAlignment="Top" Width="75"/>
    <Button Content="Cancel" Command="{Binding Path=CancelCommand}" HorizontalAlignment="Left" Margin="343,512,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>

视图模型:

using System.Collections.ObjectModel;

使用 AdminTool.DataModel.Repositories; 使用 AdminTool.Helpers;

命名空间 AdminTool.Desktop.ViewModel {

public class AccountingViewModel : ViewModelBase
{

    private ObservableCollection<CountryData> _countryList;
    public ObservableCollection<CountryData> CountryList
    {
        get { return _countryList; }
        set
        {
            _countryList = value;
            RaisePropertyChanged("CountryList");
        }
    }
    private CountryData _selectedCountry;
    public CountryData SelectedCountry
    {
        get { return _selectedCountry; }
        set
        {
            _selectedCountry = value;
            RaisePropertyChanged("SelectedCountry");
        }
    }

    private string currencyCode;

    public string CurrencyCode
    {
        get { return currencyCode; }
        set {
                currencyCode = value;
                SelectedCountry.IsChanged = true;
            }
    }

    private bool updateButtonEnabled = false;
    public bool UpdateButtonEnabled
    {
        get { return updateButtonEnabled; }
        set { updateButtonEnabled = value;
              RaisePropertyChanged("UpdateButtonEnabled");
            }
    }


    #region Commands -----------------------------------------------------------------------------------
    public RelayCommand SaveCommand { get; set; }
    public RelayCommand CancelCommand { get; set; }
    #endregion

    /// <summary>
    /// Initializes a new instance of the MainViewModel class.
    /// </summary>
    public AccountingViewModel()
    {
        SaveCommand = new RelayCommand(Save);
        CancelCommand = new RelayCommand(Cancel);

        AccountingRepository repo = new AccountingRepository();
        CountryList = repo.GetCountryList();
    }

    #region Public methods -----------------------------------------------------------------------------
    void Save(object parameter)
    {
        AccountingRepository repo = new AccountingRepository();
        repo.SaveCountryList(CountryList);
    }

    void Cancel(object parameter)
    {
    }
    #endregion
}

}

提前感谢您的帮助。

【问题讨论】:

  • 我不知道你是否处理了事件属性更改?

标签: c# wpf mvvm binding datagrid


【解决方案1】:

您需要更改模型。实现如下所示的通知接口。

模型 - 更新 name 属性

public class CountryData : INotifyPropertyChanged
{
    private string countryName;
    public string CountryName
    {
        get { return countryName; }
        set
        {
            countryName = value;
            RaisePropertyChanged("CountryName");
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string prop)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
    }

}

查看 - 在网格中使用 UpdateSourceTrigger=PropertyChangedBindings

<Grid>
    <DataGrid Name="dgCountryList" 
          ItemsSource="{Binding CountryList, Mode=TwoWay}"
          SelectedItem="{Binding Path=SelectedCountry, Mode=TwoWay}"
          HorizontalAlignment="Left" VerticalAlignment="Top" Height="450" Width="450" Margin="20,20,0,0"
          AutoGenerateColumns="False"
          SelectionMode="Single"
          SelectionUnit="FullRow"
          GridLinesVisibility="All"
          CanUserDeleteRows="True"
          CanUserAddRows="True">
        <DataGrid.RowStyle>
            <Style TargetType="{x:Type DataGridRow}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=IsChanged}" Value="true" >
                        <Setter Property="Background" Value="LightGreen" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.RowStyle>
        <DataGrid.Columns>
            <!--<DataGridTextColumn Header="ID" Binding="{Binding ID}" Width="50" />-->
            <DataGridTextColumn Header="Country" Binding="{Binding Path=CountryName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="250" />

        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Save" Command="{Binding Path=SaveCommand}" IsEnabled="{Binding Path=UpdateButtonEnabled}" HorizontalAlignment="Left" Margin="223,512,0,0" VerticalAlignment="Top" Width="75"/>
    <Button Content="Cancel" Command="{Binding Path=CancelCommand}" HorizontalAlignment="Left" Margin="343,512,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>

【讨论】:

  • @Jesper Hostrup Hansen,欢迎您。请将此标记为答案,
【解决方案2】:

您必须处理属性更改事件:

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

【讨论】:

  • 它在我的 ViewModelBase 类中,它实现了 INotifyPropertyChanged
猜你喜欢
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 2015-11-24
  • 2011-06-22
相关资源
最近更新 更多