Dan Champagne
Dan Champagne

Reputation: 920

Change Displayed attribute with MVVM object binding

I have a couple WPF windows that data-bind to view model classes that expose public properties.

<Window x:Class="OIAFMS.Presentation.Win.Views.AllLedgerEntries"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:vm="clr-namespace:OIAFMS.Presentation.Win.ViewModels"     
    Height="350" Width="525">
<Window.DataContext>
    <vm:AllLedgerEntriesViewModel />
</Window.DataContext>
<Grid>
    <DataGrid Grid.Row="0" ItemsSource="{Binding Path=ViewModels}" />
</Grid>

This ties back to an a class which exposes the ViewModels property:

    public List<LedgerEntryViewModel> ViewModels {
        get {
            List<LedgerEntryViewModel> collection = new List<LedgerEntryViewModel>();
            foreach (var item in _Service.GetAll()) {
                collection.Add(new LedgerEntryViewModel(item, _Service));
            }

            return collection;
        }
    }

Within the individual model, I have the following:

    public decimal ContributionAmt {
        get { return _Model.ContributionAmt; }
        set {
            _Model.ContributionAmt = value;
            OnPropertyChanged("ContributionAmt");
        }
    }

What I'm trying to do is see if I can add a DisplayName attribute or something else so that I could change the way this is displayed on the screen (from "ContributionAmt" to "Contribution Amount").

i.e.

    [DisplayName("Contribuion Amount")]
    public decimal ContributionAmt {
        get { return _Model.ContributionAmt; }
        set {
            _Model.ContributionAmt = value;
            OnPropertyChanged("ContributionAmt");
        }
    }

As it is now, this is how it shows.

DataGrid displayed

Is there any way I can go about this?

Upvotes: 0

Views: 87

Answers (1)

Dan Champagne
Dan Champagne

Reputation: 920

Got it!

    private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) {
        string displayName = ((PropertyDescriptor)e.PropertyDescriptor).DisplayName as string;

        if (displayName != null) {
            e.Column.Header = displayName;
        }
    }

Upvotes: 1

Related Questions