DataBinding到计算字段

时间:2011-03-26 03:06:05

标签: c# wpf data-binding entity-framework-4

我遇到了一个小问题,我正在尝试将DataGrid的DataTextColumn绑定到计算字段。

WPF

<DataGrid ItemsSource="{Binding Path=CurrentRoster, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
          AutoGenerateColumns="False" 
          AlternatingRowBackground="Gainsboro"  
          AlternationCount="2">
    <DataGrid.Columns>
    <DataGridComboBoxColumn Header="Student Enrolled"
                            ItemsSource="{Binding Source={StaticResource AvailableStudents}}"
                            SelectedItemBinding="{Binding Path=Student}">
    </DataGridComboBoxColumn>
    <DataGridTextColumn Header="Registration" Binding="{Binding Path=RegistrationCosts, StringFormat='{}{0:C}'}"/>
    <DataGridTextColumn Header="Lodging" Binding="{Binding Path=LodgingCosts, StringFormat='{}{0:C}'}"/>
    <DataGridTextColumn Header="Travel" Binding="{Binding Path=TravelCosts, StringFormat='{}{0:C}'}"/>
    <DataGridTextColumn Header="Dining" Binding="{Binding Path=DiningCosts, StringFormat='{}{0:C}'}"/>
    <DataGridTextColumn Header="Total Costs" IsReadOnly="True" Binding="{Binding Path=TotalCosts, StringFormat='{}{0:C}'}"/>
</DataGrid.Columns>

其中Student是一个实体对象,只有一个小的添加。 TotalCosts不是db表中的一个字段,所以我为此创建了一个partial类。

public partial class Student
{
    public  Decimal TotalCosts
    {
        get { return (LodgingCosts + RegistrationCosts + TravelCosts + DiningCosts); }
    }
}

我遇到的问题是,当您填写任何其他字段时,TotalCosts不会自动更新。我的猜测是因为它没有被列为依赖属性。如何为没有设置的属性解决此问题?

5 个答案:

答案 0 :(得分:3)

我假设学生实现了INotifyPropertyChanged。你要做的就是注册LodgingCosts + RegistrationCosts + TravelCosts + DiningCosts的PropertyChanged事件,并为TotalCosts举起PropertyChanged事件。

public partial class Student
{
    public Decimal TotalCosts
    {
        get { return (LodgingCosts + RegistrationCosts + TravelCosts + DiningCosts); }
    }

    public Student()
    {
        this.PropertyChanged += new PropertyChangedEventHandler(Student_PropertyChanged);
    }

    void Student_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "LodgingCosts" ||
            e.PropertyName == "RegistrationCosts" ||
            e.PropertyName == "TravelCosts" ||
            e.PropertyName == "DiningCosts")
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("TotalCosts"));
        }
    }

}

答案 1 :(得分:3)

您可以在OnPropertyChanged("TotalCosts")依赖的每个媒体资源的设置者中调用TotalCosts,它会刷新绑定

答案 2 :(得分:3)

您好o我想我可以帮助您在sqlServer中为数据库提供此代码 我有一个数据源与我的数据库的数据集

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using TestDeDataGrid.TestDSTableAdapters;

namespace TestDeDataGrid
{

    public partial class MainWindow : Window
    {
        //private ICollection<TablaTest> registros;

        public MainWindow()
        {
            InitializeComponent();

            TestDS ds = new TestDS();
            TablaTestTableAdapter adapter = new TablaTestTableAdapter();
            adapter.Fill(ds.TablaTest);


            TablaTestGrid.ItemsSource = ds.TablaTest.DefaultView;
        }


        private void TablaTestGrid_CurrentCellChanged(object sender, EventArgs e)
        {
            if ((String)(((DataGrid)sender).CurrentColumn.Header) == "A/B")
                ((DataGrid)sender).CommitEdit(DataGridEditingUnit.Row, true);
        }
    }
}

有了这个技巧,我有一个值后自动计算C列 在A列和B列中,例如,如果我在columna A中放置10,在B列中放置5 然后我按Tab键移动到columnC,值2自动出现 无需单击其他行或按Enter键。

ColumnC是表达式(ColumnaA / ColumnaB)和类型的计算列 System.Decimal。

还有我的xaml代码:

<DataGrid Name="TablaTestGrid" Grid.Row="1" AutoGenerateColumns="False"                    
              CurrentCellChanged="TablaTestGrid_CurrentCellChanged">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding Path=IdTablaTest}" IsReadOnly="True"></DataGridTextColumn>
            <DataGridTextColumn Header="Col A" Binding="{Binding Path=ColumnaA}"></DataGridTextColumn>
            <DataGridTextColumn Header="Col B" Binding="{Binding Path=ColumnaB}"></DataGridTextColumn>
            <DataGridTextColumn Header="A/B" Binding="{Binding Path=ColumnaC}" IsReadOnly="True" ></DataGridTextColumn>               
            <DataGridTextColumn Header="TestOnly"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

答案 3 :(得分:1)

DataSourceUpdateMode创建为OnPropertyChanged属性时,只需将DataBinding更改为TotalCosts

答案 4 :(得分:0)

您需要在课程上实施INotifyPropertyChanged。这是例子:

public class Person : INotifyPropertyChanged
{
    //public int Id
    //{ get; set; }

    //public string Name { get; set; }

    private int _Id;

    public int Id
    {
        get { return _Id; }
        set { _Id = value;
        RaisePropertyChanged("Id");
        }
    }

    private string _EmpNo
    {
        get
        {
            return Id.ToString() + Name.ToString();
        }
    }

    private string _Name;

    public string Name
    {
        get { return _Name; }
        set
        {
            _Name = value;
            RaisePropertyChanged("Name");
        }
    }

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

    public event PropertyChangedEventHandler PropertyChanged;
}

XAML代码:

<DockPanel>
    <TextBox Text="{Binding P1.Id}" Height="50" Width="100" DockPanel.Dock="Top" />
    <TextBox Text="{Binding P1.Name}" Height="50" Width="100" DockPanel.Dock="Top" />
    <Button Content="OK" Click="Button_Click" DockPanel.Dock="Bottom"/>
</DockPanel>

测试:

public TestWindow()
{
    InitializeComponent();

    this.DataContext = this;
}

private Person _P1 = new Person();

public Person P1
{
    get { return _P1; }
    set { _P1 = value; }
}

private void Button_Click(object sender, RoutedEventArgs e)
{

}

在2个文本框中输入内容..然后在按钮上单击,查看人员的值P1 ..u将找到带有值的计算字段。  希望它能帮到你.. 谢谢, BHavik