2012-04-17 5 views
3

WPFでは、 "{StaticResource key}"のキーを変数にバインドすることは可能ですか?<object property = "{StaticResource key}" ... />を値にバインドする

たとえば、私は変数を持っていますExecutionState アクティブ完了を持つ実行状態です。私が代わりに

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

を持つの

<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> 

を持っている私のResourceDictionaryで

私は状態は、テキストの色の変更を変更する場合はこのように

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

のようなものを持っていると思います。 このようなことも可能ですか? トリガーを使用して機能を実現できますが、いくつかの場所で再利用する必要があり、コードを乱雑にしたくありません。 MVVMも使用しています。

thanx

答えて

0

いいえ、不可能です。バインドはDependencyPropertyでのみ設定できます。 StaticResourceはDependencyObjectではないため、DependencyPropertyはありません。トリガーを使用するか、独自の動作を開発する必要があります。

0

達成する直接的な方法はありません。 1つの添付プロパティを作成し、バインドするプロパティ名を割り当てます。 プロパティ変更コールバック関数の更新制御スタイルで。

<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; 
      } 
     } 
    } 
} 
関連する問題