通过多重绑定,我能够设置特定细胞的背景。但是,我想将单元格文本的水平对齐设置为右边,但这会混淆应该拉伸整个背景的背景颜色(而不仅仅是对齐的文本) ):
这是缩小(可运行)代码
public partial class MainWindow : Window
{
public ObservableCollection<Test> MyData { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
MyData = Test.GetData();
}
}
public class Test
{
public string Title { get; set; }
public string ColOne { get; set; }
public string ColTwo { get; set; }
public static ObservableCollection<Test> GetData()
{
return new ObservableCollection<Test>
{
new Test { Title = "HO", ColOne = "3.20", ColTwo = "5.85"},
new Test { Title = "DOR", ColOne = "-3.33", ColTwo = "5.9"}
};
}
}
和XAML
<Window x:Class="ColorColumnAlignment.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid ItemsSource="{Binding Path=MyData}">
<DataGrid.Resources>
<Style TargetType="DataGridCell">
<Style.Setters>
<Setter Property="HorizontalAlignment" Value="Right"></Setter>
<Setter Property="Background" Value="Chocolate"></Setter>
</Style.Setters>
</Style>
</DataGrid.Resources>
</DataGrid>
</Grid>
</Window>
我见过有类似问题的人,但我不明白他试图解释的是他的解决方案(WPF: DataGridCell override the row style color)
- 更新:设置HorizontalContentAlignment完全没有不帮助,导致这个(右边的对齐方式已经消失了):
答案 0 :(得分:0)
将您的TargetType和Setter属性更改为以下修改后的代码中的示例:
<Window x:Class="ColorColumnAlignment.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid ItemsSource="{Binding Path=MyData}">
<DataGrid.Resources>
<Style TargetType="{x:Type TextBlock}">
<Style.Setters>
<Setter Property="TextAlignment" Value="Right" />
<Setter Property="Background" Value="Chocolate" />
</Style.Setters>
</Style>
</DataGrid.Resources>
</DataGrid>
</Grid>
</Window>
答案 1 :(得分:0)
我找到了这个解决方案:
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Foreground" Value="{StaticResource Text}"/>
<Setter Property="Background" Value="{StaticResource Foreground}"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>