Mat*_*ias 9 xaml mvvm viewmodel windows-8 windows-runtime
我的WinRT/C#XAML Metro应用程序中有一个奇怪的问题,使用Windows 8 Release Preview(安装了最新的补丁).我正在使用a ComboBox,其值ItemsSource和SelectedValue绑定到ViewModel中的属性:
<ComboBox SelectedValue="{Binding MySelectedValue, Mode=TwoWay}"
ItemsSource="{Binding MyItemsSource, Mode=OneWay}"
Width="200" Height="30" />
Run Code Online (Sandbox Code Playgroud)
代码背后:
public MainPage()
{
this.InitializeComponent();
DataContext = new TestViewModel();
}
Run Code Online (Sandbox Code Playgroud)
一个非常简单的定义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"));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我认为这个简单的解决方案应该正常工作......但是当我启动应用程序时,SelectedValue="Test Item 2"它没有显示,ComboBox而是留空.通过设置断点,我注意到绑定值,MyItemsSource并MySelectedValue在设置视图时从视图模型中进行核心检索DataContext.执行此操作后,该ComboBox.SelectedValue属性实际设置为"Test Item 2",但它只是没有显示!另外我注意到,当我在UI上通过用户操作更改ComboBox中的选定值时,更改的值显示在ComboBox中,并且View Model属性会相应地更新.所以除了MySelectedValueView Model属性的初始可视化之外,一切似乎都能正常工作.我变得非常绝望......
虽然这是最简单的例子,但在原点我想将整个实体绑定到ComboBox,设置DisplayMemberPath和SelectedValuePath.不幸的是,出现了同样的问题.
Mat*_*ias 30
我在我的示例中发现了问题:在XAML标记中,我在SelectedValue属性之前定义了ItemsSource属性.如果我以这种方式交换两个定义,它的工作原理:
<ComboBox ItemsSource="{Binding MyItemsSource, Mode=OneWay}"
SelectedValue="{Binding MySelectedValue, Mode=TwoWay}"
Width="200" Height="30" />
Run Code Online (Sandbox Code Playgroud)
这真是奇怪而烦人.现在我想知道:这是一个bug还是设计?我认为这是一个错误,因为无论XAML中定义属性的顺序如何,控件都应该正常工作.
| 归档时间: |
|
| 查看次数: |
9426 次 |
| 最近记录: |