我想根據資料行中的資料動態設定資料網格的列中的行的樣式,因此根據該屬性的值,只有一個屬性,我想在我的 3 種不同樣式之間進行選擇在資源字典中有。
我正在嘗試這個解決方案:
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell" BasedOn="{StaticResource ResourceKey=DataGridCellLeftHorizontalAlignment}">
<Style.Triggers>
<DataTrigger Binding="{Binding NumeroLineaFactura}" Value="-1">
<Setter Property="FontWeight" Value="Bold"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.CellStyle>
但這有一個問題,我只能選擇其中一種樣式,其余的屬性我必須一一更改,所以我必須在各個列中設定樣式,這讓我重復代碼。
我想可以使用資料觸發器或轉換器來選擇樣式,但我不知道可以做到這一點的語法,因為在觸發器中我既可以設定屬性樣式也不能設定 CellStryle。
如何動態設定單元格樣式?
謝謝。
uj5u.com熱心網友回復:
由于沒有CellStyleSelector可用的屬性并且您不能使用 aDataTrigger來更改Style自身,因此您應該使用單個Style然后使用多個DataTriggers來更改 的屬性DataGridCell,例如:
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding NumeroLineaFactura}" Value="-1">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="TextAlignment" Value="Right"/>
</DataTrigger>
</Style.Triggers>
</Style>
謝謝。在這種情況下它可以作業,但如果我有另一列的 -1 值具有相同的樣式,我必須重復代碼......
對。在這種情況下,您可以考慮實作自己的自定義 DataGridTextColumn 并以編程方式設定CellStyle. 像這樣的東西:
public class CustomDataGridTextColumn : DataGridTextColumn
{
public static readonly DependencyProperty FirstStyleProperty = DependencyProperty.Register(
name: nameof(FirstStyle),
propertyType: typeof(Style),
ownerType: typeof(CustomDataGridTextColumn)));
public Style FirstStyle
{
get => (Style)GetValue(FirstStyleProperty);
set => SetValue(FirstStyleProperty, value);
}
//...
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
FrameworkElement element = base.GenerateElement(cell, dataItem);
var val = dataItem as YourClass;
if(val != null)
{
switch (val.NumeroLineaFactura)
{
case -1:
cell.Style = FirstStyle;
break;
//...
}
}
return element;
}
}
XAML: :
<DataGrid.Columns>
<local:CustomDataGridTextColumn ... FirstStyle="{StaticResource yourFirstStyle}" />
</DataGrid.Columns>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/461823.html
標籤:wpf
