Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to bind 2 properties into a single DataGrid field?

Tags:

c#

binding

wpf

xaml

At the moment I have the following:

<DataGridTextColumn Header="Customer Name" 
    x:Name="columnCustomerSurname" 
    Binding="{Binding Path=Customer.FullName}" SortMemberPath="Customer.Surname"
    IsReadOnly="True">
</DataGridTextColumn>

where Customer.FullName is defined as:

public string FullName
{
    get { return string.Format("{0} {1}", this.Forename, this.Surname); }
}

The binding works, but not ideally.

If someone updates the Forename or Surname properties the update is not reflected in the DataGrid until it is refreshed.

I found issues similar to this, e.g. https://stackoverflow.com/a/5407354/181771 which uses MultiBinding but this works with a TextBlock rather than with a DataGrid.

Is there another way for me to get this working?

like image 872
DaveDev Avatar asked Oct 11 '25 19:10

DaveDev


2 Answers

One option would be to create a compound template column based on two textblocks which would still allow the form to update when changes to either property are made.

eg.

<DataGridTemplateColumn Header="Customer Name">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Path=Customer.ForeName}"/>
                <TextBlock Text="{Binding Path=Customer.SurName}"/>
            </StackPanel>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
like image 174
klaverty Avatar answered Oct 14 '25 09:10

klaverty


You should raise a property change notification for FullName from both Forename and Surname, e.g.

public string Forename
{
    get{ return _forename; }
    set
    {
        if(value != _forename)
        {
            _forename = value;
            RaisePropertyChanged("Forename");
            RaisePropertyChanged("Fullname");
        }
    }
}

Or, you cache the generated value of FullName like this

public string Forename
{
    get{ return _forename; }
    set
    {
        if(value != _forename)
        {
            _forename = value;
            RaisePropertyChanged("Forename");
            UpdateFullName();
        }
    }
}

private void UpdateFullName()
{  
    FullName = string.Format("{0} {1}", this.Forename, this.Surname); 
}

public string FullName
{
    get{ return _fullname; }
    private set
    {
        if(value != _fullname)
        {
            _fullname = value;
            RaisePropertyChanged("FullName");
        }
    }
}
like image 31
Phil Avatar answered Oct 14 '25 11:10

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!