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

后端 未结 4 555
半阙折子戏
半阙折子戏 2021-01-17 14:03

I have a simple window :



        
相关标签:
4条回答
  • 2021-01-17 14:39

    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,

    0 讨论(0)
  • 2021-01-17 14:40

    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}" />

    0 讨论(0)
  • 2021-01-17 14:40

    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.

    0 讨论(0)
  • 2021-01-17 15:01

    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>
    
    0 讨论(0)
提交回复
热议问题