![](/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.