WPF: Setting ItemSource in XAML vs. code-behind

前端 未结 2 1904
长发绾君心
长发绾君心 2021-01-12 08:37

Since this is WPF, it may look like lots of code, but don\'t be frightened, the question is really simple!

I have the following XAML:



        
2条回答
  •  梦毁少年i
    2021-01-12 09:33

    This:

    
    

    means "Bind ItemsSource to the property this.DataContext.AllRoles" where this is the current element.

    Hello.ItemsSource = AllRoles;
    

    means "Bind ItemsSource to an ObservableCollection full of roles", which directly does what you were trying to do originally.

    There are a number of ways to do this in xaml. Here's one:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
            var allRoles = new ObservableCollection()
            allRoles.Add(new Role("John", "Manager"));
            allRoles.Add(new Role("Anne", "Trainee"));
            this.DataContext = allRoles;
        }
    }
    

    and in the xaml

    
    

    OR, alternatively, you could make AllRoles a public property of the window

    public partial class MainWindow : Window
    {
        public ObservableCollection AllRoles {get;private set;}
        public MainWindow()
        {
            this.InitializeComponent();
            var allRoles = new ObservableCollection()
            allRoles.Add(new Role("John", "Manager"));
            allRoles.Add(new Role("Anne", "Trainee"));
            this.AllRoles = allRoles;
        }
    }
    

    and then use a RelativeSource to tell the Binding to walk up the logical tree to the Window

    
    

    Which means "Look at my ancestry until you find a Window, then look for a public property on the window called AllRoles".

    But the best way to do this is to skip the frigging codebehind altogether and use the MVVM pattern. I'd suggest if you're learning that you skip directly to the MVVM pattern. The learning curve is steep, but you learn all about binding and commands and the important, cool things about WPF.

提交回复
热议问题