如何在以下代码中使用 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"/>
我测试了其他绑定(bind),它们有效。我正在正确设置 DataContext。 构造函数中的 m_selectedElement = 2 将组合框中的选定元素设置为列表中的第三个。 SelectedElement 属性的 get() 方法会被调用,但 set() 方法不会被调用。我通过放置断点来检查这一点。我做错了什么?
此外,是否可以将 Platform::Array^ 绑定(bind)到 ComboBox? 我尝试使用 Platform::Array < Platform::String ^>^ 以及 Platform::Array < int>^ 但无法正常工作。 STL 容器也不起作用。可以绑定(bind)到组合框的其他可能容器是什么?
最佳答案
改变
SelectedIndex="{Binding Path=SelectedElement}"
至
SelectedIndex="{Binding Path=SelectedElement, Mode=TwoWay}"
如果您希望 UI 更新 ViewModel,则需要双向绑定(bind)。
您只能在绑定(bind)中使用 WinRT 组件(引用类/结构、枚举类)。当用于绑定(bind)时,使用 Platform::Collections::Vector 通常是正确的选择,特别是因为它还实现了 IObservableVector。 STL 容器不起作用,因为它们无法跨 ABI 传输。
关于xaml - 数据绑定(bind)到 ComboBox c++/cx XAML Metro 应用程序时 SelectedValue、SelectedIndex 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13773338/