How can I bind an ItemsControl.ItemsSource with a property in XAML?

一世执手 提交于 2019-12-19 16:15:47

问题


I have a simple window :

<Window x:Class="WinActivityManager"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <ListView x:Name="lvItems" />
    </Grid>
</Window>

And the associated code behind :

public partial class WinActivityManager : Window
{
    private ObservableCollection<Activity> Activities { get; set; }

    public WinActivityManager()
    {
        Activities = new ObservableCollection<Activity>();
        InitializeComponent();
    }

    // Other code ...
}

If I write the following binding in the window constructor :

lvItems.ItemsSource = Activities;

then my ListView is automatically updated when I add or remove elements from Activities.

How should I write the binding in XAML?
I tried this but it doesn't work:

<ListView x:Name="lvItems" ItemsSource="{Binding=Activities}" />

How do I make this work in XAML?


回答1:


What @JesseJames says is true but not enough.

You have to put

private ObservableCollection<Activity> Activities { get; set; } 

as

public ObservableCollection<Activity> Activities { get; set; }

And the binding should be:

<ListView x:Name="lvItems" ItemsSource="{Binding Path=Activities}" />

Regards,




回答2:


You must set DataContext to this like others answered, but you can set DataContext through xaml also:

<Window x:Class="WinActivityManager"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
        <ListView x:Name="lvItems" ItemsSource="{Binding Path=Activities}" />
    </Grid>
</Window>



回答3:


Set DataContext = this in the Window constructor.

public WinActivityManager()
{
    Activities = new ObservableCollection<Activity>();
    DataContext = this;
    InitializeComponent();
}

Then you will be able to bind Activities as you want: <ListView x:Name="lvItems" ItemsSource="{Binding=Activities}" />




回答4:


That's because the data context of your view hasn't been set. You could either do this in the code behind:

this.DataContext = this;

Alternatively, you could set the Window's DataContext to itself - DataContext="{Binding RelativeSource={RelativeSource Self}}"

You're much better off though investigating the MVVM design pattern, and using an MVVM framework.



来源:https://stackoverflow.com/questions/16694327/how-can-i-bind-an-itemscontrol-itemssource-with-a-property-in-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!