WPF's DataContext questions

戏子无情 提交于 2019-12-01 12:56:36
  • Yes that is correct as far as i know, since this is quite repetetive some MVVM frameworks do this linking for you.

  • In XAML:

    <UserControl ...
                 xmlns:vm="clr-namespace:MyApp.ViewModels">
        <UserControl.DataContext>
            <vm:MyViewModel />
        </UserControl.DataContext>
        <!-- ... -->
    </UserControl>
    
  • It enables short bindings where the Path is relative to the DataContext, e.g. {Binding Name} binds to DataContext.Name. It also is inherited which can be useful.

Please read the Data Binding Overview if you haven't.

The DataContext is really one of the main keys to the binding system in WPF. When you design your View (the XAML), you're setting up data bindings, but these are all being done by name (effectively, as a string). The "nearest" DataContext up the visual hierarchy is the object that WPF uses to find the matching property (by name) and wire up the binding.

The suggestion of putting the comment in place is a good one - it helps because the names chosen really depend on the ViewModel (DataContext), so a View's XAML file is really tied to a specific type of DataContext.

Note also that there are other approaches available to wire up the DataContext other than setting it in code behind, including using locators, DataTemplates, setting it directly in XAML, etc.

1 - The INotifyPropertyChanged interface updates the property changes to the UI,

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String info)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
}

2- We can use two ways to set the data context to the view , one option is to set the context in code behind file, but this is tightly coupled with view and its not a good approach, i would suggest the below option, its loosly coupled with the view

<UserControl ...
         xmlns:vm="clr-namespace:MyApp.ViewModels">
<UserControl.DataContext>
    <vm:MyViewModel />
</UserControl.DataContext>
<!-- ... -->

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