微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在xaml中绑定?

如何解决如何在xaml中绑定?

| 现在我正在这样做绑定: 领域:
private readonly RestaurantContext m_context = new RestaurantContext();
在里面:
m_context.Load(m_context.GetGroupQuery());
this.dataGridGroup.DataContext = m_context.Groups;
在xaml中怎么做?     

解决方法

Juste公开您的
m_context
,确保将封装此属性的类设置为视图的数据上下文,并将
dataGridGroup
数据上下文绑定到您的财产。 例如 :
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>
    ,在您的XAML中:
<DataGrid x:Name=\"dataGridGroup\" DataContext={Binding Groups} />
它将自动绑定到
ViewModel
Groups
属性     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。