У меня есть рабочий ProgressBar, отображаемый в одном столбце. Но вместо этого нужно, чтобы он охватывал всю строку. Как этого можно достичь?
Это работает, ProgressBar в одном столбце:
<UserControl.Resources>
<SolidColorBrush x:Key = "DgGridLineBrush" Color = "LightGray" />
<Style x:Key = "ProgressBarStyle" TargetType = "ProgressBar">
<Setter Property = "Template">
<Setter.Value>
<ControlTemplate TargetType = "ProgressBar">
<Grid x:Name = "PART_Track" >
<Rectangle x:Name = "PART_Indicator" Fill = "{Binding [3]}" HorizontalAlignment = "Left" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<DataGrid x:Name = "MbpDg" HeadersVisibility = "Column" AutoGenerateColumns = "False" IsReadOnly = "True" CanUserAddRows = "False" HorizontalAlignment = "Right" ColumnHeaderHeight = "20" Height = "221" Margin = "0,1,0,0" VerticalAlignment = "Top" Width = "164"
GridLinesVisibility = "None" >
<DataGrid.Columns>
<DataGridTemplateColumn Header = "Size" Width = "55">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<ProgressBar Value = "{Binding [2], Mode=OneWay}" Style = "{StaticResource ProgressBarStyle}" Minimum = "0" Maximum = "100"/>
<TextBlock Text = "{Binding [2], Mode=OneWay}" HorizontalAlignment = "Right"/>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Binding = "{Binding [0]}" Header = "Price" Width = "50"/>
<DataGridTextColumn Binding = "{Binding [1]}" Header = "Qty" Width = "30*"/>
</DataGrid.Columns>
Я видел этот вопрос, но попытка включить его дает обязательные исключения. Честно говоря, я не знаю, что я здесь делаю.
<Setter Property = "DataGrid.Template">
<Setter.Value>
<ControlTemplate TargetType = "{x:Type DataGridRow}">
<Grid>
<ProgressBar Value = "{Binding [2], Mode=OneWay}" Style = "{StaticResource ProgressBarStyle}" Minimum = "0" Maximum = "100"/>
</Grid>
</ControlTemplate>
</Setter.Value>
Обновлено: Ответ работал отлично, но осталась с этой "ошибкой", отображаемой три раза:
System.Windows.Data Error: 1 : Cannot create default converter to perform 'one-way' conversions between types 'System.Boolean' and 'System.Windows.Controls.SelectiveScrollingOrientation'. Consider using Converter property of Binding. BindingExpression:Path=AreRowDetailsFrozen; DataItem='DataGrid' (Name='MyDg'); target element is 'DataGridDetailsPresenter' (Name=''); target property is 'SelectiveScrollingOrientation' (type 'SelectiveScrollingOrientation')
System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='False' BindingExpression:Path=AreRowDetailsFrozen; DataItem='DataGrid' (Name='MyDg'); target element is 'DataGridDetailsPresenter' (Name=''); target property is 'SelectiveScrollingOrientation' (type 'SelectiveScrollingOrientation')
Вот Руководство , но было бы лучше сделать это по-другому





Вам нужно будет создать шаблон DataGridRow. Сначала добавьте временный DataGridRow в качестве дочернего элемента вашего DataGrid, поместите курсор на этот элемент, а затем в окне свойств перейдите в «Разное» -> «Шаблон», щелкните маленький квадрат справа от него и выберите «Преобразовать в новый ресурс». . Это создаст новый шаблон DataGridRow в вашем блоке ресурсов, который вы затем сможете установить с помощью стиля. (По какой-то причине это также заставляет заголовки строк отображаться на моем компьютере, поэтому либо удалите их из шаблона, либо просто установите `RowHeaderWidth='0' в вашем DataGrid).
Что касается отображения индикатора выполнения, просто добавьте его в качестве первого дочернего элемента SelectiveScrollingGrid в шаблоне (если вы не удалили первый столбец, вам также необходимо установить для него Grid.Column значение 1).
Соберите все это вместе, и ваше объявление DataGrid будет выглядеть примерно так (я добавил привязку ItemsSource, которую вы, вероятно, захотите удалить):
<DataGrid x:Name = "MbpDg" ItemsSource = "{Binding Items}" HeadersVisibility = "Column" AutoGenerateColumns = "False" IsReadOnly = "True" CanUserAddRows = "False" HorizontalAlignment = "Left" ColumnHeaderHeight = "20" Height = "221" Margin = "0,1,0,0" VerticalAlignment = "Top" Width = "164" CanUserResizeRows = "False" GridLinesVisibility = "None">
<DataGrid.Columns>
<DataGridTextColumn Binding = "{Binding [2]}" Header = "Size" Width = "50"/>
<DataGridTextColumn Binding = "{Binding [0]}" Header = "Price" Width = "50"/>
<DataGridTextColumn Binding = "{Binding [1]}" Header = "Qty" Width = "30*"/>
</DataGrid.Columns>
</DataGrid>
Установите стиль в блоке ресурсов:
<Style TargetType = "{x:Type DataGridRow}">
<Setter Property = "Template" Value = "{DynamicResource DataGridRowControlTemplate1}" />
</Style>
А вот и сам шаблон:
<ControlTemplate x:Key = "DataGridRowControlTemplate1" TargetType = "{x:Type DataGridRow}">
<Border x:Name = "DGR_Border" BorderBrush = "{TemplateBinding BorderBrush}" BorderThickness = "{TemplateBinding BorderThickness}" Background = "{TemplateBinding Background}" SnapsToDevicePixels = "True">
<SelectiveScrollingGrid SelectiveScrollingOrientation = "None">
<SelectiveScrollingGrid.RowDefinitions>
<RowDefinition Height = "*"/>
<RowDefinition Height = "Auto"/>
</SelectiveScrollingGrid.RowDefinitions>
<ProgressBar HorizontalAlignment = "Stretch" Value = "{Binding [2]}" Minimum = "0" Maximum = "100"/>
<DataGridCellsPresenter ItemsPanel = "{TemplateBinding ItemsPanel}" SnapsToDevicePixels = "{TemplateBinding SnapsToDevicePixels}"/>
<DataGridDetailsPresenter Grid.Row = "1" Visibility = "{TemplateBinding DetailsVisibility}" />
</SelectiveScrollingGrid>
</Border>
</ControlTemplate>
Результат:
Превосходно! Хотя у меня осталась «Ошибка System.Windows.Data» (см. редактирование). Это то, что можно/нужно решать?
Если я не ошибаюсь, вам не нужны ячейки для прокрутки, и в этом случае я думаю, что вы можете просто удалить весь этот раздел XAML и явно установить SelectiveScrollingOrientation = "None" в SelectiveScrollingGrid (вы всегда можете изменить его на что-то другое позже, если вам нужно к). Я обновил свой код соответственно.
Объединение ячеек помогло бы, но недостатком является то, что требуется много кода.