2

次のコードでComboBoxの選択された要素の値を使用するにはどうすればよいですか?

C ++:

namespace testtesttest
{
[Windows::UI::Xaml::Data::Bindable]
public ref class Wrapper sealed : Windows::UI::Xaml::Data::INotifyPropertyChanged
{
public:
    Wrapper()
    {
        // the index of the selected element of the combobox when the application starts
        m_selectedElement = 2;

        m_myStringArray = ref new Platform::Collections::Vector<int>(3);
        // 1, 2, and 4 in the combobox list
        m_myStringArray->SetAt(0,1);
        m_myStringArray->SetAt(1,2);
        m_myStringArray->SetAt(2,4);
    }

    virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;


    property Windows::Foundation::Collections::IVector<int>^ MyStringArray
    {
        Windows::Foundation::Collections::IVector<int>^ get() { return m_myStringArray; }
    }

    property int SelectedElement
    {
        int get() { return m_selectedElement; }
        void set(int value) { m_selectedElement = value; RaisePropertyChanged("SelectedElement"); }
    }
protected:
    void RaisePropertyChanged(Platform::String^ propertyName)
    {
        PropertyChanged(this, ref new Windows::UI::Xaml::Data::PropertyChangedEventArgs(propertyName));
    }
private:
    Platform::Collections::Vector<int>^ m_myStringArray;
    int m_selectedElement;
};
}

XAML:

<TextBlock HorizontalAlignment="Left" 
           Height="73" Margin="50,436,0,0" 
           TextWrapping="Wrap" 
           Text="{Binding Path=SelectedElement}" 
           VerticalAlignment="Top" 
           Width="200"/>
<ComboBox ItemsSource="{Binding Path=MyStringArray}" 
          SelectedIndex="{Binding Path=SelectedElement}"  
          HorizontalAlignment="Left" 
          Height="50" Margin="369,50,0,0" 
          VerticalAlignment="Top" Width="286"/>

他のバインディングをテストしたところ、機能しました。DataContextを正しく設定しています。コンストラクターのm_selectedElement=2は、コンボボックスで選択された要素をリストの3番目に設定します。SelectedElementプロパティのget()メソッドが呼び出されますが、set()メソッドは呼び出されません。ブレークポイントを設定してこれを確認しました。私は何が間違っているのですか?

また、Platform :: Array ^をComboBoxにバインドすることは可能ですか?Platform :: Array <Platform :: String^>^とPlatform::Array <int> ^を使用してみましたが、動作しませんでした。STLコンテナも機能しませんでした。コンボボックスにバインドできる他の可能なコンテナは何ですか?

4

1 に答える 1

2

変化する

SelectedIndex="{Binding Path=SelectedElement}" 

SelectedIndex="{Binding Path=SelectedElement, Mode=TwoWay}"

UIでViewModelを更新する場合は、双方向バインディングが必要です。

WinRTコンポーネントは、バインディング(refクラス/構造体、列挙型クラス)でのみ使用できます。Platform :: Collections :: Vectorを使用することは、特にIObservableVectorも実装しているため、バインディングに使用する場合は一般的に正しい選択です。STLコンテナは、ABIを通過できないため、機能しません。

于 2012-12-08T01:33:02.960 に答える