[英]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
您需要執行此操作,在包含Style
的Resources
屬性中的實際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.