【发布时间】:2014-08-28 02:39:09
【问题描述】:
通过多重绑定,我能够设置特定单元格的背景。但是,我想将单元格文本的水平对齐设置为向右,但这会弄乱 background color 应该 stretch 完整的背景(不仅仅是对齐的文本):
这是缩小(可运行)的代码
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 确实没有完全有帮助,它会导致这个(右对齐不知何故消失了):
【问题讨论】:
-
用
HorizontalContentAlignment交换HorizontalAlignment -
@ChrisW。不,这没有帮助。它保持与左侧对齐,我已经尝试过了
-
哦,抱歉,试试 TextAlignment,我不记得该属性是否可用,否则您可能需要考虑复制(或)编辑默认样式模板以适合您的需要。
-
@ChrisW。 TextAlignment 不是 DataGridCell 属性的一部分。
-
是的,我不这么认为,但也没有花时间检查。我会继续查看default templates,我们将在其中看到 ContentPresenter 绑定到 HorizontalContentAlignment 的 HorizontalAlignment。您可能只想指定自己的模板来实现您的目标。
标签: c# xaml background alignment wpfdatagrid