简体   繁体   English

ListBox 到字符串 ObservableCollection 的简单 WPF 数据绑定

[英]Simple WPF DataBinding of a ListBox to an ObservableCollection of strings

Okay, I just don't get it.好吧,我就是不明白。 Please tell me why I get no items in my ListBox (should be the two strings "empty" and "stuff" right now ):请告诉我为什么我的 ListBox 中没有任何项目(现在应该是两个字符串“empty”和“stuff”):

XAML: XAML:

<Window.DataContext>
    <Windows:SettingsWindowModel x:Name="model"/>
</Window.DataContext>

<Window.Resources>
    <DataTemplate x:Key="ListItemTemplate">
        <ListBoxItem Content="{Binding}"  />
    </DataTemplate>
</Window.Resources>

<ListBox Name="listBoxActivities" SelectionChanged="ListBoxActivitiesSelectionChanged"
 ItemsSource="{Binding Path=IgnoredActivities}"
 HorizontalAlignment="Left" VerticalAlignment="Top" MinHeight="40" MinWidth="200"
 Padding="5,100,5,0" Height="100" Margin="0,207,0,0" ItemTemplate="{StaticResource ListItemTemplate}" />

In SettingsWindowModel:在设置窗口模型中:

    private ObservableCollection<String> _ignoredActivities;
    public ObservableCollection<String> IgnoredActivities
    {
        get
        {
            if (_ignoredActivities == null)
            {
                // empty
                _ignoredActivities = new ObservableCollection<String>() { "empty","stuff" };
            }
            return _ignoredActivities;
        }
    }

Anything more you need to know?您还需要了解什么? What did I forget?我忘记了什么?

EDIT: Maybe I should add that VisualStudio + ReSharper also show no underlines and compile errors.编辑:也许我应该补充一点,VisualStudio + ReSharper 也不显示下划线和编译错误。 Not even warnings.甚至没有警告。

Sorry guys, the data was there all the time. 抱歉,数据一直在那儿。 The problem was in the visual details. 问题出在视觉细节上。 The padding also got applied to a sub-container of the ListBox (or the items), therefore the items were not sitting at the top of the list. 填充也已应用于ListBox的子容器(或项目), 因此,项目不在列表的顶部。 As I've but a height on the ListBox, the items always were below the visible height of the ListBox . 正如我在ListBox上的高度一样,项目始终低于ListBox的可见高度 Stange thing to debug. 调试东西。 Thanks for your answers anyways! 无论如何,谢谢您的回答!

1) You don't need to set the DataTemplate 1)您不需要设置DataTemplate

2) Are you sure the DataContext of the view (aaaaa.xaml.cs) is the ViewModel (bbbbb.cs, contains IgnoredActivities)? 2)您确定视图(aaaaa.xaml.cs)的DataContext是ViewModel(bbbbb.cs,包含IgnoredActivities)吗?

It should be like this: 应该是这样的:

aaaaa.xaml: aaaaa.xaml:

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

aaaaa.xaml.cs: aaaaa.xaml.cs:

public partial class aaaaa : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new bbbbb();
    }
}

bbbbb.cs : bbbbb.cs:

    public class bbbbb : INotifyPropertyChanged
    {
        public bbbbb()
        {
            IgnoredActivities.Add("empty");
            IgnoredActivities.Add("stuff");
        }

        private ObservableCollection<String> _ignoredActivities;
        public ObservableCollection<String> IgnoredActivities
        {
            get
            {
                if (_ignoredActivities == null)
                {
                    // empty
                    _ignoredActivities = new ObservableCollection<String>() { "empty","stuff" };
                }
                return _ignoredActivities;
            }
        }

            #region INotifyPropertyChanged Members

            public event PropertyChangedEventHandler PropertyChanged;
            private void RaisePropertyChanged(string _Prop)
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs(_Prop));
            }

            #endregion
    }
}

With this statement you are binding to a property "IgnoredActivities" in a control named "model" of your Window. 使用此语句,您将绑定到Window名为“模型”的控件中的属性“ IgnoredActivities”。

ItemsSource="{Binding ElementName=model, Path=IgnoredActivities}"

When working with ViewModels, set them as the DataContext of your control: 使用ViewModels时,请将它们设置为控件的DataContext:

<ListBox ItemsSource="{Binding IgnoredActivities}">
    <ListBox.DataContext>
        <local:MyViewModel/>
    </ListBox.DataContext>        
</ListBox>

A binding with no source specified ("{Binding PathToMyPropert}") defaults to the control's DataContext, which is inherited from parent controls. 未指定源(“ {Binding PathToMyPropert}”)的绑定默认为控件的DataContext,该控件是从父控件继承的。 So in your case, you could set your ViewModel to your Window's DataContext so it will be available to all its children: 因此,在您的情况下,可以将ViewModel设置为Window的DataContext,以便其所有子级都可以使用:

<Window>
    <Window.DataContext>
        <local:MyViewModel/>
    </Window.DataContext>        

    <ListBox ItemsSource="{Binding IgnoredActivities}"/>    
</Window>

Get rid of that ElementName binding property. 摆脱那个ElementName绑定属性。 It's used to bind to WPF controls. 它用于绑定到WPF控件。 Simply set ItemsSource={Binding IgnoredActivities} 只需设置ItemsSource={Binding IgnoredActivities}

Try it as follows: 尝试如下:

<ItemsControl ItemsSource="{Binding Path=IgnoredActivities}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <ListBox />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
       <DataTemplate>
           <ListBoxItem Content="{Binding}"  />
       </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Try also setting the DataContext for the control in code behind. 还尝试在后面的代码中为控件设置DataContext。

Xaml       - <ListBox Name="myListBox" ItemsSource="{Binding IgnoredActivities}"/>    
CodeBehind - myListBox.DataContext=this;

确保DataContext包含IgnoredActivities并将ItemsSource绑定到它:

ItemsSource="{Binding IgnoredActivities}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM