[英]WPF binding to property of non-simple property of other class
在这种情况下,有点无法弄清楚如何使用WPF绑定:
假设,我们有一个具有CarInfo类型的非简单属性的对象Car:
public class CarInfo : DependencyObject
{
public static readonly DependencyProperty MaxSpeedProperty =
DependencyProperty.Register("MaxSpeed", typeof (double), typeof (CarInfo), new PropertyMetadata(0.0));
public double MaxSpeed
{
get { return (double) GetValue(MaxSpeedProperty); }
set { SetValue(MaxSpeedProperty, value); }
}
}
public class Car : DependencyObject
{
public static readonly DependencyProperty InfoProperty =
DependencyProperty.Register("Info", typeof (CarInfo), typeof (Car), new PropertyMetadata(null));
public CarInfo Info
{
get { return (CarInfo) GetValue(InfoProperty); }
set { SetValue(InfoProperty, value); }
}
}
还假设,Car是一个ui元素,它有Car.xaml,很简单:
<Style TargetType="assembly:Car">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="assembly:Car">
<Grid >
!--> <TextBlock Text="{Binding Path=MaxSpeed}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
所以,我想在我的Car.xaml中使用这个TextBlock来表示我的CarInfo类的属性“MaxSpeed” ,它实际上是我的Car类的属性。 我怎样才能做到这一点?
提前谢谢,感谢任何帮助! :)
它取决于分配给表示Car的UI元素的DataCOntext的内容 - 您需要指定相对于该元素的绑定路径。 在这种情况下,我建议你从这开始:
<TextBlock Text="{Binding Path=Info.MaxSpeed}" />
这假设已将Car对象分配给Car UI元素的DataContext。
请注意,您的属性不必是依赖项属性 - 您还可以绑定到普通属性(取决于您正在执行的操作)。
看来你正在寻找使用元素绑定,所以你应该能够通过使用TemplatedParent或祖先作为你的相对来源来实现你想要的。 请参阅此前的SO答案以获取示例。 你的绑定应该是这样的:
<TextBlock Text="{Binding Path=Info.MaxSpeed, RelativeSource={RelativeSource TemplatedParent}}" />
这将带您回到模板化的父控件(Car),然后沿UI元素的Info属性向下移动到其内容的MaxSpeed属性。
正如我在评论中所说的那样,通过让UI元素与数据元素紧密匹配,然后将数据对象分配给UI元素上相对非标准的属性,您就会变得非常混乱。 您可能有自己的理由,但XAML和WPF并不需要那么复杂。
<TextBlock Text="{Binding Path=Info.MaxSpeed}" />
该代码适用于我:
<TextBlock Text="{Binding Path=Info.MaxSpeed, RelativeSource={RelativeSource Mode=TemplatedParent}}" />
和用法:
Car.Info = new CarInfo { MaxSpeed = 100.0 };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.