簡體   English   中英

在Silverlight datagrid中設置DataGridHeaderBackground的背景顏色

[英]Set the background color of DataGridHeaderBackground in Silverlight datagrid

我有一個應用程序,用戶可以在運行時設置datagrid標頭的背景色。 我怎樣才能做到這一點? 我通過下面的代碼嘗試了相同的操作,但是它拋出了異常。我已經使用綁定了,但是沒有用。

var style = this.Resources["DataGridHeaderStyle"] as Style;
style.Setters.SetValue(DataGridColumnHeader.BackgroundProperty, "Red");

沒有更多詳細信息(例如您正在獲取的異常),很難理解為什么您會收到異常。 我懷疑style變量具有空引用。

我還懷疑它為null的原因是this對象的資源字典中不存在“ DataGridHeaderStyle”,我猜這是UserControl 為了獲取Style您需要執行此操作,在包含StyleResources屬性中的實際FrameworkElement對象上進行查找。 (請注意,以編程方式訪問資源並不會級聯搜索父資源的可視樹)。

但是,假設您可以解決問題,仍然可以解決。 Setters本身上使用SetValue不同於您實際需要執行的操作。

您需要這樣做:

style.Setters.Add(new Setter(DataGridColumnHeader.BackgroundProperty,  new SolidColorBrush(Colors.Red));

當然,這僅在樣式尚未包含屬性的Setter的情況下才有效。 因此,一個更強大的版本是:

var setter = style.Setters
                  .OfType<Setter>()
                  .Where(s => s.Property == DataGridColumnHeader.BackgroundProperty)
                  .FirstOrDefault();

if (setter != null)
    setter.Value = new SolidColorBrush(Colors.Red);
else
    style.Setters.Add(new Setter(DataGridColumnHeader.BackgroundProperty,  new SolidColorBrush(Colors.Red));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM