Как связать DataGridColumn. Видимость?

Ява не лучшая вещь там. Просто потому, что он поставляется с наклейкой «Предприятие», не делает его хорошим. И при этом это не делает это быстро. И это не делает его ответом на каждый вопрос.

Кроме того, ROR - это еще не все, чем занимается Blogsphere.

Пока я в этом, ООП не всегда хорош. На самом деле, я думаю, что это обычно плохо.

15
задан Community 23 May 2017 в 12:08
поделиться

4 ответа

Столбец таблицы данных наследуется от DependencyObject, а не от FrameworkElement. В WPF это не составит большого труда ... но в silverlight вы можете привязываться только к объектам FrameworkElement. Таким образом, при попытке вы получите описательное сообщение об ошибке AG_E_PARSER_BAD_PROPERTY_VALUE.

3
ответ дан 1 December 2019 в 03:24
поделиться

Из вашего класса MyDataGridTextColumn вы можете получить окружающий DataGrid. Затем вы получаете свою ViewModel из DataContext DataGrid и добавляете обработчик к событию PropertyChanged вашей ViewModel. В обработчике вы просто проверяете имя свойства и его значение и соответственно изменяете видимость столбца. Это не совсем лучшее решение, но должно работать;)

0
ответ дан 1 December 2019 в 03:24
поделиться

Крис Манчини,

вы не создаете привязку к свойству «Привязка» столбца сетки данных. Ну, вы пишете «{Binding User.UserName}», но это не создает привязку, потому что (как сказал Захари) столбец datagrid не наследуется от FrameworkElement и не имеет метода SetBinding. Таким образом, выражение «{Binding User.UserName}» просто создает объект Binding и присваивает его свойству Binding столбца (это свойство является типом Binding). Затем столбец datagrid при создании содержимого ячеек (защищенный метод GenerateElement) использует этот объект Binding для установки привязки к сгенерированным элементам (например, к свойству Text сгенерированного TextBlock), которые являются FrameworkElements

1
ответ дан 1 December 2019 в 03:24
поделиться

I don't know how much this will help, but I've run into the lack of dependency property problem with data grid columns myself in my latest project. What I did to get around it, was to create an event in the grid column view model, then when the grid is being assembled in the client, use a closure to subscribe the grid column to the column view model. My particular problem was around width. It starts with the view model class for the grid column, which looks something like this pseudo-code:

public delegate void ColumnResizedEvent(double width);

public class GridColumnViewModel : ViewModelBase
{
    public event ColumnResizedEvent ColumnResized;

    public void Resize(double newContainerWidth)
    {
        // some crazy custom sizing calculations -- don't ask...
        ResizeColumn(newWidth);
    }

    public void ResizeColumn(double width)
    {
        var handler = ColumnResized;
        if (handler != null)
            handler(width);
    }
}

Then there's the code that assembles the grid:

public class CustomGrid
{
    public CustomGrid(GridViewModel viewModel)
    {
        // some stuff that parses control metadata out of the view model.
        // viewModel.Columns is a collection of GridColumnViewModels from above.
        foreach(var column in viewModel.Columns)
        {
            var gridCol = new DataGridTextColumn( ... );
            column.ColumnResized  += delegate(double width) { gridCol.Width = new DataGridLength(width); };
        }
    }
}

When the datagrid is resized in the application, the resize event is picked up and calls the resize method on the viewmodel the grid is bound to. This in turn calls the resize method of each grid column view model. The grid column view model then raises the ColumnResized event, which the data grid text column is subscribed to, and it's width is updated.

I realise this isn't directly solving your problem, but it was a way I could "bind" a view model to a data grid column when there are no dependency properties on it. The closure is a simple construct that nicely encapsulates the behaviour I wanted, and is quite understandable to someone coming along behind me. I think it's not too hard to imagine how it could be modified to cope with visibility changing. You could even wire the event handler up in the load event of the page/user control.

2
ответ дан 1 December 2019 в 03:24
поделиться
Другие вопросы по тегам:

Похожие вопросы: