XAML将命令参数绑定到DataGrid列名

时间:2017-01-08 14:47:25

标签: c# wpf xaml mvvm datagrid

我正在使用Galasoft MVVM Light。我有一个DataGrid,有四列,包括总额,增值税税率,增值税金额和净额。当用户更改其中一个值时,我需要重新计算其他三个值。我有一个附加到DataGrid的CellEditEnding事件的relay命令,以激活ViewModel中进行计算的代码。但我需要知道哪个值已被更改才能正确进行计算。如何在XAML中指定哪个列/单元触发了事件,即如何将命令参数绑定到触发列/单元的名称?

<DataGrid
     ....>
<i:Interaction.Triggers>
    <i:EventTrigger EventName="CellEditEnding">
        <mvvm:EventToCommand Command="{Binding  CalculateAusgabe_Command, 
                    Mode=OneWay, 
                    UpdateSourceTrigger=PropertyChanged, 
                    diag:PresentationTraceSources.TraceLevel=High}"
              CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridTextColumn}}, Path=Name}" />
    </i:EventTrigger>
</i:Interaction.Triggers>
</DataGrid>

在ViewModel中,代码为:

public RelayCommand<string> CalculateAusgabe_Command { get; set; }
...
CalculateAusgabe_Command = new RelayCommand<string>(CalculateAusgabe);

最后是进行计算的程序:

void CalculateAusgabe(string colName)
{
    if (currBetrag.USt == null) return;
    switch (colName)
    {
        case "colBetBtto":
        case "colBetUStS":
            if (currBetrag.BttoBetrag != 0M)
            {
                currBetrag.UStBetrag = Math.Round((currBetrag.BttoBetrag / (100M + currBetrag.USt.UStProz)) * currBetrag.USt.UStProz, 2);
                currBetrag.NttoBetrag = currBetrag.BttoBetrag - currBetrag.UStBetrag;
            }
            break;
        case "colBetUStB":
        ...

DataGrid的当前行绑定到currBetrag对象。一切正常,触发事件时会激活CalculateAusgabe,但无论我做什么,参数colName始终为null。对此问题的任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

您可以在currBetrag类的setter中执行计算,例如:

public class currBetrag : INotifyPropertyChanged
{
    private decimal _bttoBetrag;
    public decimal BttoBetrag
    {
        get { return _bttoBetrag; }
        set
        {
            _bttoBetrag = value;
            OnPropertyChanged();

            CalculateAusgabe("BttoBetrag");
        }
    }

    private decimal _uStBetrag;
    public decimal UStBetrag
    {
        get { return _uStBetrag; }
        set
        {
            _uStBetrag = value;
            OnPropertyChanged();

            CalculateAusgabe("UStBetrag");
        }
    }

    private void CalculateAusgabe(string colName)
    {
        if (USt == null) return;
        switch (colName)
        {
            //set the value of all fields...
            _uStBetrag = ?;
        }

        //and raise the PropertyChanged event for all involved properties
        OnPropertyChanged("UStBetrag");
        OnPropertyChanged("NttoBetrag");
        //...
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
     }
}

请注意,不管您的母语是什么,都不会使用英语成员名称。