在mvvm中选择的列表框第一项 [英] Listbox First Item Selected in mvvm

查看:88
本文介绍了在mvvm中选择的列表框第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是mvvm的新手.我的Silverlight应用程序中有一个列表框,该列表框已绑定到视图模型中的一个可观察集合,我想使列表框具有选中的第一项.我对此感到厌倦,但它不起作用.

I am new to mvvm. I have a listbox in my silverlight application which is binded to a observable collection in view model i want to make the listbox with first item selected. I tired this but it doesnt work.

<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">

然后我在主页视图模型的主页加载中添加了此内容

then i added this in mainpage load of mainpage viewmodel

CurrentCategory = Categorys[0];

任何人都可以帮助我

推荐答案

执行以下步骤:

  1. 确保已经填充了集合Categorys.您可能需要使用 AsycCTP,带有Async和Await的异步编程或其他方法另一种机制是首先等待集合被填满.

  1. Make sure that the collection Categorys is filled already. You might need to use AsycCTP, Asynchronous Programming with Async and Await or some other mechanism to first wait for the collection to be filled.

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.

  • 在ViewModel中实现INotifyPropertyChanged,从而暴露PropertyCurrentCategory并从PropertySetter内部引发PropertyChanged事件.

  • Implement INotifyPropertyChanged in ViewModel exposing the Property, CurrentCategory and raise the event of PropertyChanged from within the Setter of the Property.

    private Category _currentCategory = null;
    
    public Category CurrentCategory 
    {
        get { return _currentCategory; }
        set
        {
            if (_currentCategory != value)
            { 
                _currentCategory = value;
    
                // Update bindings
                RaisePropertyChanged("CurrentCategory");
            }
        }
    }
    

  • 现在您可以使用同一段代码:

    Now you can use the same piece of code:

    CurrentCategory = Categorys[0];
    

    这篇关于在mvvm中选择的列表框第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆