gpt4 book ai didi

wpf - 绑定(bind)到 WPF 中当前数据上下文/源属性的父级/同级

转载 作者:行者123 更新时间:2023-12-01 23:09:34 24 4
gpt4 key购买 nike

我们如何绑定(bind)到当前数据上下文的父级/同级(即表示当前数据上下文的源属性)?

我不是在谈论绑定(bind)到父控件的属性(这种情况涉及目标的父级而不是源的父级) - 这可以通过使用RelativeSourceMode=FindAncestor 轻松完成。

RelativeSourceMode=PreviousData 提供对绑定(bind)到数据项的前一个同级项的有限支持,但不支持绑定(bind)到父项或其他同级项。

虚拟示例:
(假设 INPC 就位)
如何将ComboBox的ItemsSource绑定(bind)到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" });
}
}

XAML:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="300" Width="300">
<Grid>
<DataGrid ItemsSource="{Binding Persons}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Departments???}"
SelectedValue="{Binding Department}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>

最佳答案

您可以像这样访问祖先 DataContext:

<ComboBox ItemsSource="{Binding DataContext.Departments, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}}"
SelectedValue="{Binding Department}"/>

关于wpf - 绑定(bind)到 WPF 中当前数据上下文/源属性的父级/同级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5764810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com