【问题标题】:Unable to fill in a ListBox in WPF using MVVM无法使用 MVVM 在 WPF 中填写 ListBox
【发布时间】:2014-08-22 08:31:31
【问题描述】:

嗨,我想用可观察集合的项目填充列表框。我的 XAML 文件中有:

<catel:UserControl x:Class="Musat.Classificator.CatelMVVM.Views.StopControlView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:catel="http://catel.codeplex.com"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">

<catel:UserControl.Resources>
    <CollectionViewSource Source="{Binding Something}" x:Key="cvsStops" />        
</catel:UserControl.Resources>

<catel:StackGrid x:Name="LayoutRoot">
    <ListBox ItemsSource="{Binding Source={StaticResource cvsStops}}" />
</catel:StackGrid>

在我的 ViewModel 中我有:

 class StopViewModel : ViewModelBase
{
   public StopViewModel()
    {
        ObservableCollection<String> Something = new ObservableCollection<String>();
        Something.Add("A");
        Something.Add("B");
        Something.Add("C");
        Something.Add("D");
        Something.Add("E");
        Something.Add("F");      
    }
}

但是列表框没有填充任何数据。有没有因为找不到而做错了什么?

【问题讨论】:

  • 为什么要通过静态资源绑定而不是直接绑定?
  • 还有一点,catel:UserControl的DataContext在哪里设置
  • 我不认为这是问题
  • Something 是属性吗?一个DP?它是否实现了 INotiftyPropertyChanged?请发布完整的代码。
  • @user3182266 目前Something 是构造函数的局部变量,它需要是StopViewModel 的公共属性,StopControlViewDataContext 也必须相应设置

标签: c# wpf xaml mvvm listbox


【解决方案1】:

我们在这里有点猜测,但它会这么简单吗?您必须绑定到属性(使用 INotifyPropertyChanged)或 DO 中的依赖属性。

    private ObservableCollection<string> something = new ObservableCollection<String> { "A", "B", "C", "D", "E", "F" };
    public ObservableCollection<String> Something // Must be property or DP to be bound!
    {
        get { return something; }
        set
        {
            if (Equals(value, something)) return;
            something = value;
            RaisePropertyChanged("Something");
        }
    }

没有完整的代码很难说。你是如何设置你的数据上下文的?为什么不直接绑定到这个属性?

<ListBox ItemsSource="{Binding Something}"/>

在启动应用程序时检查您的调试输出。

干杯

斯蒂安

【讨论】:

  • 好吧,我该死。我知道我搞砸了,只是不知道我愿意让我的收藏成为财产,对此感到抱歉,但再次非常感谢你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 2013-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-16
  • 2015-07-01
相关资源
最近更新 更多