c# - 在 mvvm 中选择的列表框第一项

标签 c# xaml mvvm silverlight-4.0

我是 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/

    相关文章:

    c# - 在流文档中跨列跨文本

    wpf - 如何添加验证以查看模型属性或如何实现 INotifyDataErrorInfo

    wpf - 如何将 WPF 中的命令绑定(bind)到控件的双击事件处理程序?

    c# - 文件名 : Why? 中的 0x202A

    c# - 为什么 XmlSerializer 在 Visual Studio 2019 中不会导致 FileNotFoundException?

    c# - 无法在 Visual Studio 2015 中通过 NuGet 安装 EmguCV

    .net - WPF - 编译错误 : Tags of type 'PropertyArrayStart' are not supported in template sections

    C# 如何删除整数中的第 n 位?

    wpf - 如何使用单独程序集的嵌入图像?

    wpf - 如何删除正在使用Datavisualization工具包dll的Wpf图表中的点