8

私はいくつかのアプリケーションであり、いくつかのテキストボックスとチェックボックスをDictionary(列挙型、文字列)の値フィールドにバインドしたいと思います。これは可能ですか?どうすればそれを行うことができますか?

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}" />

..そしてこれが私が列挙型に持っているものです

public enum MyEnum
{
    PrimaryAddress,
    SecondaryAddress,
    UsePrimaryAddress
}

ViewModelディクショナリでは、次のように定義されています。

public Dictionary<MyEnum, string> Properties

列挙値を持つコンボボックスの解決策を見つけましたが、これは私の場合には当てはまりません。

何かアドバイス?

4

1 に答える 1

13

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

モデルを見る:

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();
    }
}

詳細については、「バインディング パスの構文」を参照してください。

于 2012-10-02T13:08:08.363 に答える