![](/img/trans.png)
[英]How to change background of DataGridCell when IsEditing=True in WPF
[英]WPF - setting datagridcell background AND horizontal alignment messes up background
通过多重绑定,我能够设置特定细胞的背景。 但是,我想将单元格文本的horizontalalignment设置为正确,但这弄乱了应该拉伸整个背景的背景颜色 (不仅限于对齐的文本):
这是最小的(可运行的)代码
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覆盖行样式的颜色 )
-更新:设置HorizontalContentAlignment并不能完全解决问题,这会导致这种情况(右对齐以某种方式消失了):
将您的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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.