2013-04-03 108 views
1

我想更改WPF中DataGrid的RowHeader的背景。我做了一个静态资源的风格,并希望在C#中添加样式。以下是XAML/C#中的代码。更改DataGridRowHeaderStyle(背景)?

XAML:

<Window x:Class="GUI.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"> 
<Window.Resources> 
    <Style x:Name="newRowHeader" TargetType="{x:Type DataGridRowHeader}"> 
     <Setter Property="Background" Value="White" /> 
    </Style> 
</Window.Resources> 
<Grid Name="MainGrid"> 
</Grid> 

C#:

System.Windows.Controls.DataGrid dg = new System.Windows.Controls.DataGrid(); 
dg.RowHeaderStyle = (Style)FindResource("newRowHeader"); 

在C#dg.RowHeaderStyle的最后一行时出现错误....。错误:'在类型'GUI.MainWindow'上匹配指定的绑定约束的构造函数的调用抛出异常。

请帮忙

回答

0

你在哪里运行这段代码?它在构造函数里面?如果是,则尝试在窗口加载时执行此操作:

public MainWindow(){ 
    //... 
    Loaded+=(_,e)=>{ 
     System.Windows.Controls.DataGrid dg = new System.Windows.Controls.DataGrid(); 
     dg.RowHeaderStyle = (Style)FindResource("newRowHeader"); 
    }; 
} 

也许是窗口尚未加载。希望它有帮助...

0

解决了它。应该使用资源[“x:Key”]。