【问题标题】:WPF Listbox binding problemsWPF列表框绑定问题
【发布时间】:2017-01-12 16:44:56
【问题描述】:

我正在创建一个 N 层 wpf mvvm 项目。我想从数据库中获取要显示在列表框中的项目列表。我想将列表框绑定到 ViewModel (VM) 中的属性。问题是绑定对我不起作用,列表框总是空的。 当我在“返回标签”上放置断点时,它会在显示表单之前完全填充。

MainWindow() 构造函数中的DataContext = App.ViewModel;

在我的 XAML 中

    <ListBox ItemsSource="{Binding Tags, Mode=OneWay}" Height="161" HorizontalAlignment="Left" Margin="236,6,0,0" Name="lstTags" VerticalAlignment="Top" Width="130" >
             <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Vertical">
                            <TextBlock Text="{Binding Tags.Name}" />
                            <TextBlock Text="{Binding Tags.Description}" />
                            <!--<CheckBox IsChecked="{Binding Deleted, Mode=TwoWay}"/>-->
                        </StackPanel>
                    </DataTemplate>
             </ListBox.ItemTemplate>
    </ListBox>

在我的虚拟机中:当我在“返回标签”上设置断点时,它已完全填充。

private TagCol _tags;
public TagCol Tags
{
    get {
        TagColData tcd = new TagColData();
        _tags = tcd.LoadAll();

        //NotifyPropertyChanged("Tags");

        return _tags; 
    }
    set {
        _tags = value;
        NotifyPropertyChanged("Tags");
    }
}

TagCol:

公共类 TagCol { 私有 ObservableCollection _tagCol = new ObservableCollection();

/// <summary>Collection (list) of Tag objects</summary>
public ObservableCollection<Tag> Collection { 
    get { return _tagCol; } 
    set 
    { 
        _tagCol = value;
    } 
}

public TagCol()
{

}

}

【问题讨论】:

  • 您是否将 MainWindow(或 ListBox 的任何父控件)的 DataContext 设置为您的视图模型类的实例?
  • 能否包含TagCol 的定义
  • 使用 Snoop 在运行时检查绑定和控件。 TagCol 必须实现 IEnumerable 才能工作。
  • 大家好。我已经用 TagCol 类更新了这个问题。 Clemens DataContext 是在 MainWindow() 构造函数中设置的。
  • Snoop 很有趣,虽然有点吓人,它会像这样扰乱您的应用程序。谢谢。

标签: c# wpf xaml mvvm listbox


【解决方案1】:

伙计们,它当然在绑定中,需要将其设置为 Tags.Collection 顺便说一句,在文本框 Collection.Name 的子属性中不起作用。

这花了几天的空闲时间! :)

        <ListBox ItemsSource="{Binding Tags.Collection}" Height="161" HorizontalAlignment="Left" Margin="236,6,0,0" Name="lstTags" VerticalAlignment="Top" Width="130" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                        <TextBlock Text="{Binding Path=Name}" />
                        <TextBlock Text="{Binding Path=Description}" />
                        <CheckBox IsChecked="{Binding Deleted, Mode=TwoWay}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

【讨论】:

    猜你喜欢
    • 2012-12-16
    • 2011-11-05
    • 1970-01-01
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    相关资源
    最近更新 更多