我的 WinRT/C# XAML Metro 应用程序使用 Windows 8 Release Preview(安装了最新补丁)时遇到了一个奇怪的问题。我正在使用 ComboBox
,其值 ItemsSource
和 SelectedValue
绑定(bind)到 ViewModel 中的属性:
<ComboBox SelectedValue="{Binding MySelectedValue, Mode=TwoWay}"
ItemsSource="{Binding MyItemsSource, Mode=OneWay}"
Width="200" Height="30" />
后面的代码:
public MainPage()
{
this.InitializeComponent();
DataContext = new TestViewModel();
}
TestViewModel
的一个非常简单的定义,使用字符串:public class TestViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private IEnumerable<string> _myItemsSource = new List<string>
{
"Test Item 1",
"Test Item 2",
"Test Item 3"
};
public IEnumerable<string> MyItemsSource
{
get { return _myItemsSource; }
}
private string _mySelectedValue = "Test Item 2";
public string MySelectedValue
{
get { return _mySelectedValue; }
set
{
_mySelectedValue = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("MySelectedValue"));
}
}
}
}
现在我认为这个简单的解决方案应该可以工作......但是当我启动应用程序时,
SelectedValue="Test Item 2"
没有出现,ComboBox
留空。通过设置断点,我注意到绑定(bind)值 MyItemsSource
和 MySelectedValue
当我设置 DataContext
时从 View 模型中正确检索到的看法。执行此操作后,ComboBox.SelectedValue
属性实际上设置为 "Test Item 2"
,但它只是没有显示!我还注意到,当我通过 UI 上的用户操作更改 ComboBox 中的选定值时,更改的值会显示在 ComboBox 中,并且 View Model 属性也会相应更新。因此,除了 MySelectedValue
的初始可视化之外,一切似乎都运行良好。查看模型属性。我真的越来越绝望了……现在虽然这是最简单的例子,但在原点我想将整个实体绑定(bind)到 ComboBox,设置
DisplayMemberPath
和 SelectedValuePath
.不幸的是,同样的问题发生了。
最佳答案
我在示例中发现了问题:在 XAML 标记中,我定义了 SelectedValue
房产 之前 ItemsSource
属性(property)。如果我以这种方式交换两个定义,它会起作用:
<ComboBox ItemsSource="{Binding MyItemsSource, Mode=OneWay}"
SelectedValue="{Binding MySelectedValue, Mode=TwoWay}"
Width="200" Height="30" />
这真的很奇怪也很烦人。现在我想知道:这是一个错误还是设计使然?我认为这是一个错误,因为无论 XAML 中定义的属性的顺序如何,控件都应该正常工作。
关于xaml - 组合框 SelectedValue 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11482573/