2011-01-30 10 views
2

コントロールのタイプがUIElementCollectionButtonsです。このようなプロパティをトリガ(具体的にはDataTrigger)で変更することは可能ですか?私は次のコードしているXAMLトリガーセッターとUIElementCollectionタイプのプロパティ

は:

<Setter Property="Buttons"> 
    <Setter.Value> 
     <Button>A</Button> 
     <Button>B</Button> 
    </Setter.Value> 
</Setter> 

そして私は、「プロパティの値が複数回設定されている」エラーが発生します。 UIElementCollectionタグ内のボタンをラップすることはできません(UIElementCollectionにはデフォルトのコンストラクタがありません)。 2番目のボタンを削除した場合、ButtonsプロパティがタイプButtonと互換性がないという例外があります。任意の助け

おかげ

答えて

0

最後に、私は変更することで問題を回避することにしましたコレクション全体を変更するのではなく、コレクションの個々の項目(個々のボタン)をトリガーします。

一部の条件によっては、ボタンを非表示にするだけです。

2

編集:回避策は、コンバータを使用することだろう、いくつかのリソースのリストにあなたのボタンを定義します。

<col:ArrayList x:Key="Buttons"> 
     <Button>A</Button> 
     <Button>B</Button> 
    </col:ArrayList> 

名前空間:xmlns:col="clr-namespace:System.Collections;assembly=mscorlib"

と使用をセッターのカスタムコンバーターをコレクションに変換する:

<Setter Property="Buttons" Value="{Binding Source={StaticResource Buttons}, Converter={StaticResource ListToUIElementCollectionConverter}}"/> 

編集:これを正しく実行することは、コンバータがUIElementCollectionコンストラクタの親オブジェクトを知る必要があるため、簡単な作業ではありません。

+0

私は、UIElementCollectionにはデフォルトのコンストラクタがないので、元の投稿では動作しません。おそらく、もし私がIListを実装しているItemsControl派生コンテナを作ったとしてもうまくいくかもしれませんが、ちょっと不器用です。 –

+0

質問をよく読んでください。私の心に来たものはコンバーターを使っていましたが、それを私の答えに加えました。どちらかといえばそれほどうれしい。 –

3

添付の動作を使用して、セッターでコレクションを変更できます。ここにもUIElementCollectionあるPanel.Childrenプロパティに基づいて実施例である:

<Grid> 
    <Grid.Resources> 
     <Style x:Key="twoButtons" TargetType="Panel"> 
      <Setter Property="local:SetCollection.Children"> 
       <Setter.Value> 
        <x:Array Type="UIElement"> 
         <Button Content="Button1"/> 
         <Button Content="Button2"/> 
        </x:Array> 
       </Setter.Value> 
      </Setter> 
     </Style> 
    </Grid.Resources> 
    <StackPanel Style="{StaticResource twoButtons}"/> 
</Grid> 

そしてここでは、添付プロパティSetCollection.Children次のとおりです。

public static class SetCollection 
{ 
    public static ICollection<UIElement> GetChildren(DependencyObject obj) 
    { 
     return (ICollection<UIElement>)obj.GetValue(ChildrenProperty); 
    } 

    public static void SetChildren(DependencyObject obj, ICollection<UIElement> value) 
    { 
     obj.SetValue(ChildrenProperty, value); 
    } 

    public static readonly DependencyProperty ChildrenProperty = 
     DependencyProperty.RegisterAttached("Children", typeof(ICollection<UIElement>), typeof(SetCollection), new UIPropertyMetadata(OnChildrenPropertyChanged)); 

    static void OnChildrenPropertyChanged(object sender, DependencyPropertyChangedEventArgs e) 
    { 
     var panel = sender as Panel; 
     var children = e.NewValue as ICollection<UIElement>; 
     panel.Children.Clear(); 
     foreach (var child in children) panel.Children.Add(child); 
    } 
} 
関連する問題