Monday, November 25, 2013

Class design advice

Here's a great "step back and think" article I came across on StackOverflow on class design.
Its always so tempting to just dive in and write some code, which usually turns into a heavy refactor cycle.

http://stackoverflow.com/a/4203836/553404

Thursday, November 14, 2013

Get ListboxItem from a the bound SelectedItem


In my case the ListBox is bound to an IEnumerable<Transaction>.  Where Transaction is a custom type in my domain model.

        <ListBox x:Name="TransactionListBox"
                     ItemsSource="{Binding Statement.Transactions}"
                     SelectedItem="{Binding SelectedTransaction}" />
... 
        private ListBoxItem GetSelectedListBoxItem()
        {
            object transaction = this.TransactionListBox.SelectedItem;
            return (ListBoxItem) this.TransactionListBox.ItemContainerGenerator.ContainerFromItem(transaction);
        }

Get DataGridCell given row and column index


        private static DataGridCell GetCell(DataGrid grid, DataGridRow row, int column)
        {
            if (row != null)
            {
                var presenter = GetVisualChild<DataGridCellsPresenter>(row);

                if (presenter == null)
                {
                    grid.ScrollIntoView(row, grid.Columns[column]);
                    presenter = GetVisualChild<DataGridCellsPresenter>(row);
                }

                var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                return cell;
            }
            return null;
        }

Find a Child Element in the Visual Tree Programmatically


        private static T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);

            for (int i = 0; i < numVisuals; i++)
            {
                var v = (Visual) VisualTreeHelper.GetChild(parent, i);
                child = v as T;
                if (child == null)
                {
                    child = GetVisualChild<T>(v);
                }
                if (child != null)
                {
                    break;
                }
            }
            return child;
        }

Finding a DataGridRow based on row index in WPF


        private static DataGridRow GetRow(DataGrid grid, int index)
        {
            var row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
            if (row == null)
            {
                // May be virtualized, bring into view and try again.
                grid.UpdateLayout();
                if (index >= grid.Items.Count)
                {
                    index = grid.Items.Count - 1;
                }

                grid.ScrollIntoView(grid.Items[index]);
                row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
            }
            return row;
        }