有没有一种简单的方法来指定 WPF 数据绑定,其中路径是一个“级别”?向上?
诚然,这个例子有点做作,但我正在做类似的事情。假设我有以下简单的类:
public class Person
{
public string Name { get; set; }
public List<Alias> Aliases { get; set; }
}
public class Alias
{
public string AliasName { get; set; }
}
假设我有一个带有 LayoutRoot 网格的 Xaml 和一个 DataGrid,我想在其中访问 DataGrid 中的 Name 属性,而不是像下面的 Aliases 属性那样第二列:
<Grid x:Name="LayoutRoot" DataContext="PersonInstance">
<DataGrid ItemsSource="{Binding Aliases}">
<DataGrid.Columns>
<data:DataGridTextColumn Header="AliasName" Binding="{Binding AliasName, Mode=TwoWay}"/>
<data:DataGridTextColumn Header="Name" Binding="{Binding ../Name, Mode=TwoWay}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
直观上,这就是我尝试绑定名称的方式,但不用说,这看起来很愚蠢。指定路径时是否有类似的情况,或者您是否被迫获取 LayoutRoot 数据上下文的相对源。如果必须的话,最有效的方法是什么?
This example is a admittedly a little contrived but I am doing something similar. Let's say I have the following simple classes:
public class Person
{
public string Name { get; set; }
public List<Alias> Aliases { get; set; }
}
public class Alias
{
public string AliasName { get; set; }
}
And let's say that I have Xaml with a LayoutRoot grid, and a DataGrid where I want to access the Name property within the DataGrid instead of the Aliases properties like in the second column here:
<Grid x:Name="LayoutRoot" DataContext="PersonInstance">
<DataGrid ItemsSource="{Binding Aliases}">
<DataGrid.Columns>
<data:DataGridTextColumn Header="AliasName" Binding="{Binding AliasName, Mode=TwoWay}"/>
<data:DataGridTextColumn Header="Name" Binding="{Binding ../Name, Mode=TwoWay}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
That is intuitively how I would attempt to bind the name, but needless to say that looks stupid. Is there something like that when specifying a path, or are you forced to get a relative source up to the LayoutRoot data context. If you have to, what's the most efficient way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该对您有用:
您可以使用以下任何一种:
使源元素等于给定类型的最接近父元素:
使源元素等于给定类型的第 n 个最接近父元素:
使源元素等于给定类型数据绑定集合中的前一个数据项:
This should work for you :
You can use any of the following :
To make the source element equal the closest parent of a given type:
To make the source element equal the nth closest parent of a given type:
To make the source element equal the previous data item in a data-bound collection:
我认为没有比使用树上的相对源更好的方法了。您可以重写您的模型(例如,从
Alias
添加对父Person
的引用),但这并不是更好的方法。从性能的角度来看,我从未发现相对源绑定中的瓶颈。总有其他因素让您的应用程序无法达到火箭般的速度。
I think there is no better way to do this than using relative source up the tree. You could rewrite your model (for example, add a reference to parent
Person
fromAlias
) but that's hardly better approach.From performance prospective I never found bottlenecks in relative source bindings. There's always something else that keeps your app away from rocket speed.