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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13647951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:26:06  来源:igfitidea点击:

Simple WPF DataBinding of a ListBox to an ObservableCollection of strings

c#.netwpfdata-binding.net-4.0

提问by Akku

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. Not even warnings.

编辑:也许我应该补充一点,VisualStudio + ReSharper 也没有显示下划线和编译错误。甚至没有警告。

回答by Akku

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. As I've but a height on the ListBox, the items always were below the visible height of the ListBox. Stange thing to debug. Thanks for your answers anyways!

对不起各位,数据一直在那里。问题在于视觉细节。填充也应用于 ListBox(或项目)的子容器,因此项目不在列表的顶部。因为我在 ListBox 上只有一个高度,所以项目总是低于 ListBox 的可见高度。奇怪的事情要调试。无论如何,感谢您的回答!

回答by amnezjak

Get rid of that ElementNamebinding property. It's used to bind to WPF controls. Simply set ItemsSource={Binding IgnoredActivities}

摆脱那个ElementName绑定属性。它用于绑定到 WPF 控件。简单设置ItemsSource={Binding IgnoredActivities}

回答by Geerten

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>

回答by JuStDaN

Try also setting the DataContext for the control in code behind.

还尝试在后面的代码中为控件设置 DataContext。

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

回答by Louis Kottmann

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) 您确定视图的 DataContext (aaaaa.xaml.cs) 是 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
    }
}

回答by Arthur Nunes

With this statement you are binding to a property "IgnoredActivities" in a control named "model" of your Window.

使用此语句,您将绑定到 Window 名为“model”的控件中的属性“IgnoredActivities”。

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

When working with ViewModels, set them as the DataContext of your control:

使用 ViewModel 时,将它们设置为控件的 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. So in your case, you could set your ViewModel to your Window's DataContext so it will be available to all its children:

未指定源的绑定(“{Binding PathToMyPropert}”)默认为控件的 DataContext,它是从父控件继承的。因此,在您的情况下,您可以将 ViewModel 设置为 Window 的 DataContext,以便它的所有子项都可以使用它:

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

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

回答by mihai

Make sure the DataContextcontains IgnoredActivitiesand bind ItemsSourceto it:

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

ItemsSource="{Binding IgnoredActivities}"