绑定到WPF中当前datacontext/source属性的父级/同级
如何绑定到当前datacontext的父/同级(即,表示当前datacontext的源属性) 我不是说绑定到父控件的属性(这种情况涉及目标的父控件而不是源控件的父控件),这可以通过使用RelativeSourceMode=FindAncestor轻松完成 RelativeSourceMode=PreviousData提供了绑定到数据项的前一个同级的有限支持,但不支持绑定到父级或其他同级 虚拟示例:绑定到WPF中当前datacontext/source属性的父级/同级,wpf,data-binding,Wpf,Data Binding,如何绑定到当前datacontext的父/同级(即,表示当前datacontext的源属性) 我不是说绑定到父控件的属性(这种情况涉及目标的父控件而不是源控件的父控件),这可以通过使用RelativeSourceMode=FindAncestor轻松完成 RelativeSourceMode=PreviousData提供了绑定到数据项的前一个同级的有限支持,但不支持绑定到父级或其他同级 虚拟示例: (假设INPC就位) 如何将ComboBox的ItemsSource绑定到ViewModel的De
(假设INPC就位)
如何将ComboBox的ItemsSource绑定到ViewModel的Departments属性?
public class Person
{
public string Name { get; set; }
public string Department { get; set; }
}
public class PersonViewModel
{
public List<Person> Persons { get; set; }
public List<string> Departments { get; set; }
public PersonViewModel()
{
Departments = new List<string>();
Departments.Add("Finance");
Departments.Add("HR");
Departments.Add("Marketing");
Departments.Add("Operations");
Persons = new List<Person>();
Persons.Add(new Person() { Name = "First", Department = "HR" });
Persons.Add(new Person() { Name = "Second", Department = "Marketing" });
Persons.Add(new Person() { Name = "Third", Department = "Marketing" });
}
}
公共类人物
{
公共字符串名称{get;set;}
公共字符串部门{get;set;}
}
公共类PersonViewModel
{
公共列表人员{get;set;}
公共列表部门{get;set;}
公共PersonViewModel()
{
部门=新列表();
部门。添加(“财务”);
部门。添加(“人力资源”);
部门。添加(“营销”);
部门。添加(“运营”);
人员=新列表();
添加(新人员(){Name=“First”,Department=“HR”});
添加(newperson(){Name=“Second”,Department=“Marketing”});
添加(newperson(){Name=“Third”,Department=“Marketing”});
}
}
XAML:
在大多数情况下,我使用DataContext作为路径根:
{Binding Path=DataContext.MyProperty,ElementName=MyElement}
{Binding Path=DataContext.MyProperty,RelativeSource={RelativeSource AncestorType=MyAnsectorTypr}
我不知道为什么相对资源方法不起作用。(我一直都在这样做,
AncestorType=UserControl
)但如果这是不可接受的,我会想到两种方法
1) 给每个人一份要绑定到的部门列表。在您的示例中,您可以在Person构造函数中传递列表。或者,给每个人一个对家长的引用,以获得家长的任何属性,如:{Binding parent.Departments}
2) 创建附加属性“ParentDataContext”,并将其设置在items控件之外,如下所示:
<Window local:Attached.ParentDataContext="{Binding}" ... >
附加属性必须继承,以便树中较低的所有内容都可以通过在顶层进行设置来进行设置。您可以访问这样的数据上下文:
<ComboBox ItemsSource="{Binding DataContext.Departments, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}}"
SelectedValue="{Binding Department}"/>
so{Binding DataContext.Departments,RelativeSource={RelativeSource Mode=FindAncestor,antestortype={x:Type DataGrid}}}}
不是你想要的吗?嗯。。。我不认为我可以使用父控件的DataContext属性来获取父数据项..:)。添加我的评论作为您方便的答案=)这是标准和推荐的方式吗?似乎它比其他方法(修改源属性)更容易。在我的例子中,我使用的是Telerik RadGridView,所以在上面的解决方案中,我需要使用Telerik:RadGridView更改DataGrid。
{Binding Path=(local:Attached.ParentDataContext).Departments, RelativeSource=Self}
<ComboBox ItemsSource="{Binding DataContext.Departments, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}}"
SelectedValue="{Binding Department}"/>