2

私は自分のプロジェクト内でこの ObservableCollection-Class を使用しています: Link
I want to Bind a RibbonMenuButton to a ObservableDictionary<string,bool>:

<r:RibbonMenuButton ItemsSource="{Binding MyDictionary}">
    <r:RibbonMenuButton.ItemContainerStyle>
        <Style TargetType="{x:Type r:RibbonMenuItem}">
            <Setter Property="IsCheckable" Value="true"/>
            <Setter Property="Header" Value="{Binding Path=Key}"/>
            <Setter Property="IsChecked" Value="{Binding Path=Value}"/>
        </style>
    </r:RibbonMenuButton.ItemContainerStyle>
</r:RibbonMenuButton>

しかし、内部 IDictionary-KeyValuePairs の Value-Properties が読み取り専用であるため、例外が発生します。これを解決する方法はありますか?

私は次のようなことを考えました:

<Setter Property="IsChecked" Value="{Binding Source=MyDictionary[{Binding Path=Key}]}"/>

しかし、これは {Binding} の {Binding} が原因で機能しません...

4

4 に答える 4

3

辞書は辞書としてではなく、IEnumerable<KeyValuePair<string, bool>>. したがって、それぞれが読み取り専用プロパティを持つ とRibbonMenuItemにバインドされます。 できるよKeyValuePair<string, bool>KeyValue
2ひとことs:

1.ObservableCollection<Tuple<string, bool>>辞書の代わりに an を使用し、にバインドIsCheckedItem2ます。
2. プロパティを含む小さなヘルパー クラスを作成し、IsCheckedディクショナリを変更して、そのクラスを値として含み、にバインドIsCheckedValue.IsCheckedます。

必要な変更と考えられる副作用が小さいため、答え 2 を使用します。
私の答えは、あなたが双方向バインディングをしたいことを前提としていますIsChecked。そうでない場合は、スラッグスターの答えに進みます。

于 2011-05-17T11:39:38.817 に答える
1

デフォルトでは、WPF バインディングは双方向です。一方向にして、問題が解決するかどうかを確認してください。

<r:RibbonMenuButton ItemsSource="{Binding MyDictionary}">
    <r:RibbonMenuButton.ItemContainerStyle>
        <Style TargetType="{x:Type r:RibbonMenuItem}">
            <Setter Property="IsCheckable" Value="true"/>
            <Setter Property="Header" Value="{Binding Key, Mode=OneWay}"/>
            <Setter Property="IsChecked" Value="{Binding Value, Mode=OneWay}"/>
        </style>
    </r:RibbonMenuButton.ItemContainerStyle>
</r:RibbonMenuButton>

参照先は次のとおりです: MSDN Windows Presentation Foundation Data Binding: Part 1 (具体的には、ページの下部にあるセクションBinding Modeを確認してください)

于 2011-05-17T11:39:49.350 に答える
0

辞書へのバインドに関するこの問題の一般的な解決策として、私は UpdateableKeyValuePair を作成し、通常の KeyValuePair の instaed を返します。これが私のクラスです:

   public class UpdateableKeyValuePair<TKey,TValue>
      {
      private IDictionary<TKey, TValue> _owner;
      private TKey _key;
      public UpdateableKeyValuePair(IDictionary<TKey, TValue> Owner, TKey Key_)
         {
         _owner = Owner;
         _key = Key_;
         }

      public TKey Key
         {
         get
            {
            return _key;
            }
         }

      public TValue Value
        {
        get
          {
          return _owner[_key];
          }
       set
         {
          _owner[_key] = value;
         }
      }
    }
于 2014-04-07T15:12:12.417 に答える