C# PROGRAMMING

Binding

Article by:
Date Published:
Last Modified:

The best tutorial of Binding in WPF that I’ve found is here. It includes a project download which is great for binding that works out-of-the-box, which you can then hack/adjust to your own needs.

ObservableCollection

The ObservableCollection() class is used plenty when it comes to binding.

Searching For And Selecting A Particular Element

The following code searches through an observable collection and finds items based a string match with one of the elements properties.

1
2
3
4
5
6
7
var observC = new ObservableCollection();

// Search through collection
var searchRes = observC.Where(item => item.Name == "test");

// Obtain single element
var singleElement = searchRes.Take(0);

Obtaining The Current DataContext For A UI Element

Obtaining the current DataContext for a particular UI element us useful when you want to set-up binding. The following code shows how to get the data context, obtaining the data context for the entire window (because it uses this, but you could replace this with any particular UI element if you wish).

1
2
3
4
5
class Window1 : Window {
    private void GetViewModel() {
        viewmodel vm = (viewmodel)this.DataContext;
    }
}

Authors

Geoffrey Hunter

Dude making stuff.

Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License .

Tags

    comments powered by Disqus