[WPF] DataGrid 對Abstract class 進行Binding

在正常情況下, 當WPF datagrid bind abstract class 時, 只會顯示該abstract class 內容, 而implement 的attribute 則不會出現. 這是因為這個binding 過程乃在compile time 進行而非run-time 進行. 若要實現的話, 則須要進行部份設置.

XAML 設定, 當欄更新時觸發事件.

<DataGrid AutoGenerateColumns="True" LoadingRow="DataGrid_LoadingRow">
</DataGrid>

Code-behind, 將DataContext 每個property 重新放到UI 中.

private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            var dg = sender as DataGrid;
            var pis = e.Row.DataContext.GetType().GetProperties();
            foreach (var pi in pis)
            {
                // Check if this property already has a column in the datagrid
                string name = pi.Name;
                var q = dg.Columns.Where(_ => _.SortMemberPath == name);
                if (!q.Any())
                {
                    // No column matches, so add one
                    DataGridTextColumn c = new DataGridTextColumn();
                    c.Header = name;
                    c.SortMemberPath = name;
                    System.Windows.Data.Binding b = new Binding(name);
                    c.Binding = b;

                    // All columns don't apply to all items in the list
                    // So, we need to disable the cells that aren't applicable
                    // We'll use a converter on the IsEnabled property of the cell
                    b = new Binding();
                    b.Converter = new ReadOnlyConverter();
                    b.ConverterParameter = name;
                    // aa
                    b.ValidatesOnDataErrors = true;

                    // Can't apply it directly, so we have to make a style that applies it
                    Style s = new Style(typeof(DataGridCell));
                    s.Setters.Add(new Setter(DataGridCell.IsEnabledProperty, b));
                    // Add a trigger to the style to color the background when disabled
                    var dt = new DataTrigger() { Binding = b, Value = false };
                    dt.Setters.Add(new Setter(DataGridCell.BackgroundProperty, Brushes.Silver));
                    s.Triggers.Add(dt);
                    c.CellStyle = s;

                    // Add the column to the datagrid
                    dg.Columns.Add(c);
                }
            }
        }

 

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.