KyloRen
KyloRen

Reputation: 2741

Bind Unrelated property to DataGrid

EDIT: Solved (I made another property in the ViewModel wrapper and bound to that)

I am trying to bind a property that is not related to the ObservableCollection that the DataGrid is bound to. The other columns are binding the way they should, it is just this one column that I can't seem to get to work.

I tried binding the property using RelativeSource AncestorType and directly to the DataContext with no luck.

The XAML, The ObservableCollection I am binding to obviously is called MonthlyRecords which is a collection of a different class and this is binding the way it should be. It is the property SelectedTenant.FullName which has nothing to do with the collection that is giving me grief.

<DataGrid ItemsSource="{Binding MonthlyRecords}" AutoGenerateColumns="False">
        <DataGrid.Columns>

            <DataGridTemplateColumn Header="Name">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <!--Trying to bind this Property in the next line-->
                        <TextBlock Text="{Binding Path=SelectedTenant.FullName}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

            <DataGridTextColumn Width="60" Header="Code" Binding="{Binding UpdateSourceTrigger=LostFocus, Path=TenantCode}" />

This is the class for the property I am trying to bind.

public class Tenant 
{
    public Tenant()
    {
    }

    public int Code { get; set; }
    public string LastName { get; set; }        
    public string FirstName { get; set; }        
    public string FullName => LastName + " " + FirstName;
    public string Section { get; set; }

    public Tenant(int code, string lastName = null, string firstName = null,  string section = null)
    {
        Code = code;
        LastName = lastName;            
        FirstName = firstName;            
        Section = section;
    }
}

And this is the property in the ViewModel I am trying to bind to.

private Tenant _selectedTenant;

public Tenant SelectedTenant
{
    get { return _selectedTenant; }
    set
    {
        if (Equals(_selectedTenant, value)) return;
        _selectedTenant = value;
        OnPropertyChanged();
    }
}

What else do I need to do to get this to bind to the DataGrid?

Upvotes: 1

Views: 51

Answers (1)

Sushil Mate
Sushil Mate

Reputation: 583

<DataGridTextColumn Header="Name" Binding="{Binding Path=SelectedTenant.FullName, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>

Edit:

I have set AutoGenerateColumns="True"

<DataGrid ItemsSource="{Binding MonthlyRecords}" AutoGenerateColumns="True">

<DataGridTextColumn Header="Name" Binding="{Binding ElementName=ComboBoxTenant, Path=DisplayMemberPath}"/>

Upvotes: 1

Related Questions