2011-05-24 120 views
0

現在我這樣做綁定: 領域:xaml如何綁定?

private readonly RestaurantContext m_context = new RestaurantContext(); 

初始化:

m_context.Load(m_context.GetGroupQuery()); 
this.dataGridGroup.DataContext = m_context.Groups; 

如何在XAML中做到這一點?

回答

0

在您的XAML:

<DataGrid x:Name="dataGridGroup" DataContext={Binding Groups} /> 

它會自動綁定到你的ViewModel

1

中庸之道的Groups財產暴露你m_context,確保封裝此屬性的類被設置爲在DataContext你查看並綁定您的dataGridGroup datacontext到您的屬性。

例如:

public partial class Window1 
{ 
    public Window1() 
    { 
     InitializeComponent(); 
     DataContext = new WindowViewModel();//this will set the WindowViewModel object below as the datacontext of the window 
    } 
} 

public class WindowViewModel : INotifyPropertyChanged 
{ 

    public event PropertyChangedEventHandler PropertyChanged; 

    public void InvokePropertyChanged(PropertyChangedEventArgs e) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) handler(this, e); 
    } 

    public WindowViewModel() 
    { 
     restContext = new RestaurantContext();//init 1 
     restContext.Load(restContext.GetGroupQuery());//init 2 
     InvokePropertyChanged(new PropertyChangedEventArgs("RestContext"));//notify the view th update datacontext 
    } 

    private RestaurantContext restContext; 
    /// <summary> 
    /// Gets or sets the RestContext (which will be vound to the datagrid datacontext) 
    /// </summary> 
    public RestaurantContext RestContext 
    { 
     get { return restContext; } 
     set 
     { 
      if (RestContext != value) 
      { 
       restContext = value; 
       InvokePropertyChanged(new PropertyChangedEventArgs("RestContext")); 
      } 
     } 
    } 


} 

/// <summary> 
/// Whatever class 
/// </summary> 
public class RestaurantContext 
{ 
    public void Load(object getGroupQuery) 
    { 
     //Whatever here 
    } 

    public object GetGroupQuery() 
    { 
     //Whatever here 
     return new object(); 
    } 

    IEnumerable Groups { get; set; } 
} 

XAML:

<Window x:Class="StackOverflow.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Width="100" Height="100" > 
    <Grid> 
     <DataGrid DataContex="{Binding RestContext.Groups}"></DataGrid> 
    </Grid> 
</Window>