2012-04-17 52 views
3

在WPF中,是否可以將「{StaticResource key}」中的鍵綁定到變量。將<object property =「{StaticResource key}」... />中的鍵綁定到值

例如。我有一個變量ExecutionState與狀態有效已完成

在我的ResourceDictionary我有

<Style TargetType="{x:Type TextBlock}" x:Key="Active"> 
     <Setter Property="Foreground" Value="Yellow"/> 
    </Style> 
    <Style TargetType="{x:Type TextBlock}" x:Key="Completed"> 
     <Setter Property="Foreground" Value="Green"/> 
    </Style> 

而不必

<TextBlock Style="{StaticResource Active}"/> 

的我想有一些像

<TextBlock Style="{StaticResource {Binding ExecutionState}}"/> 

因此,如果狀態更改文本顏色的變化。 甚至有可能是這樣的嗎? 我可以使用觸發器實現所需的功能,但我必須在幾個地方重複使用它,而且我不想混淆我的代碼。 我也使用MVVM。

thanx

回答

0

不,這是不可能的。綁定只能在DependencyProperty上設置。 StaticResource不是一個DependencyObject,所以沒有DependencyProperty。您應該使用觸發器或開發您自己的附加行爲。

0

沒有直接的實現方法。 創建一個附加屬性並分配要綁定的屬性名稱。 在屬性更改回調函數中更新控件樣式。

<TextBlock dep:CustomStyle.StyleName="{Binding ExecutionState}" Text="Thiru"  /> 


public static class CustomStyle 
{ 
    static FrameworkPropertyMetadata _styleMetadata = new FrameworkPropertyMetadata(
            string.Empty, FrameworkPropertyMetadataOptions.AffectsRender, StyleNamePropertyChangeCallBack); 

    public static readonly DependencyProperty StyleNameProperty = 
     DependencyProperty.RegisterAttached("StyleName", typeof (String), typeof (CustomStyle), _styleMetadata); 

    public static void SetStyleName(UIElement element, string value) 
    { 
     element.SetValue(StyleNameProperty, value); 
    } 
    public static Boolean GetStyleName(UIElement element) 
    { 
     return (Boolean)element.GetValue(StyleNameProperty); 
    } 


    public static void StyleNamePropertyChangeCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 

     FrameworkElement ctrl = d as FrameworkElement; 

     if (ctrl.IsLoaded) 
     { 

      string styleName = Convert.ToString(e.NewValue); 
      if (!string.IsNullOrEmpty(styleName)) 
      { 
       ctrl.Style = ctrl.TryFindResource(styleName) as Style; 
      } 
     } 
    } 
} 
相關問題