2012-10-02 20 views
5

私はいくつかのアプリケーションですが、いくつかのテキストボックスとチェククboxをDictionary(Enum、string)の値フィールドにバインドしたいと思います。これは可能ですか?どうすればいいですか?Dictionaryとしてenumをキーとした値のバインド

私はこのような何か持っているXAMLコードで

- それはキーとして文字列と辞書のために働いているが、それは正しく列挙

<dxe:TextEdit EditValue="{Binding Properties[PrimaryAddress], Mode=TwoWay}" /> 
<dxe:TextEdit EditValue="{Binding Properties[SecondaryAddress], Mode=TwoWay}" /> 
<dxe:CheckEdit EditValue="{Binding Properties[UsePrimaryAddress], Mode=TwoWay}" /> 

をキーにバインドすることはできません...と、ここで私が列挙型で持っているものですViewModelに辞書で

public enum MyEnum 
{ 
    PrimaryAddress, 
    SecondaryAddress, 
    UsePrimaryAddress 
} 

次のように定義されます

public Dictionary<MyEnum, string> Properties 

私はsolutを発見しましたコンボボックスの場合はenum値のイオンですが、これは私の場合には当てはまりません。

アドバイスはありますか?

答えて

9

バインディング式でインデクサーのパラメータに適切なタイプを設定する必要があります。

ビューモデル:

public enum Property 
{ 
    PrimaryAddress, 
    SecondaryAddress, 
    UsePrimaryAddress 
} 

public class ViewModel 
{ 
    public ViewModel() 
    { 
     Properties = new Dictionary<Property, object> 
     { 
      { Property.PrimaryAddress, "123" }, 
      { Property.SecondaryAddress, "456" }, 
      { Property.UsePrimaryAddress, true } 
     }; 
    } 

    public Dictionary<Property, object> Properties { get; private set; } 
} 

XAML:

<Window x:Class="WpfApplication5.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfApplication5" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition/> 
      <RowDefinition/> 
      <RowDefinition/> 
     </Grid.RowDefinitions> 

     <TextBox Grid.Row="0" Text="{Binding Path=Properties[(local:Property)PrimaryAddress]}"/> 
     <TextBox Grid.Row="1" Text="{Binding Path=Properties[(local:Property)SecondaryAddress]}"/> 
     <CheckBox Grid.Row="2" IsChecked="{Binding Path=Properties[(local:Property)UsePrimaryAddress]}"/> 
    </Grid> 
</Window> 

コードビハインド:

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     DataContext = new ViewModel(); 
    } 
} 

詳細情報については、 "Binding Path Syntax" を参照してください。

+0

上記のバインディングパスを使用すると、次のエラーが発生します。System.Windows.Data Error:40:BindingExpressionパスエラー: '['] 'オブジェクト'のプロパティが見つかりません 'Dictionary '2'(HashCode = 56465364) '' BindingExpression:Path =プロパティ[(mbpt:MyEnum)UsePrimaryAddress]; DataItem = 'MyUserControlViewModel'(HashCode = 21018822);ターゲット要素は 'CheckEdit'(Name = '')です。ターゲットプロパティは 'EditValue'(タイプ 'オブジェクト') – user1714232

+0

ええ、気にしないでください。私は道を縛るのに間違いを犯しました。あなたの解決策は今働いています。ありがとうございました :) – user1714232

関連する問題