我是 mvvm 的新手。我的 silverlight 应用程序中有一个列表框,它绑定(bind)到 View 模型中的一个可观察集合,我想制作列表框并选择第一个项目。我厌倦了这个,但它不起作用。
<ListBox Height="431" Canvas.Left="17" Canvas.Top="77" Width="215" FontSize="13" ItemsSource="{Binding Path=Categorys, Mode=TwoWay}" DataContext="{Binding}" SelectedItem="{Binding CurrentCategory, Mode=TwoWay}" ItemTemplate="{StaticResource CategoryDataTemplate}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Name="lst_category">
然后我在主页 View 模型的主页加载中添加了这个
CurrentCategory = Categorys[0];
谁能帮我
最佳答案
执行以下步骤:
Categorys
已经填满了。您可能需要使用 AsycCTP, Asynchronous Programming with Async and Await或其他一些首先等待集合被填充的机制。The await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes. The task represents ongoing work.
INotifyPropertyChanged
在 ViewModel 中暴露 Property
, CurrentCategory
并从 Setter
中引发 PropertyChanged 事件的Property
.private Category _currentCategory = null;
public Category CurrentCategory
{
get { return _currentCategory; }
set
{
if (_currentCategory != value)
{
_currentCategory = value;
// Update bindings
RaisePropertyChanged("CurrentCategory");
}
}
}
现在您可以使用相同的代码:
CurrentCategory = Categorys[0];
关于c# - 在 mvvm 中选择的列表框第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13108468/