C# WPF绑定到其他类的非简单属性的属性

C# WPF绑定到其他类的非简单属性的属性,c#,wpf,binding,C#,Wpf,Binding,在这种情况下,有一点不知道如何使用WPF绑定: 假设我们有一辆CarInfo类型的非简单属性的对象车: public class CarInfo : DependencyObject { public static readonly DependencyProperty MaxSpeedProperty = DependencyProperty.Register("MaxSpeed", typeof (double), typeof (CarInfo), new Prop

在这种情况下,有一点不知道如何使用WPF绑定:

假设我们有一辆CarInfo类型的非简单属性的对象车:

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类的一个属性。我该怎么做

提前感谢您,感谢您的帮助!:)


这取决于分配给代表汽车的UI元素的DataCOntext的内容-您需要指定与之相关的绑定路径。在这种情况下,我建议您从以下内容开始:

<TextBlock Text="{Binding Path=Info.MaxSpeed}" />

这是假设一个Car对象已分配给carui元素的DataContext

请注意,您的属性不必是依赖属性-您还可以绑定到普通属性(取决于您正在执行的操作)

编辑 看起来您希望使用元素绑定,所以您应该能够通过使用TemplatedParent或祖先作为相对源来实现所需的功能。有关示例,请参见。您的绑定应该如下所示:

<TextBlock Text="{Binding Path=Info.MaxSpeed, RelativeSource={RelativeSource TemplatedParent}}" />

这将带您回到模板化的父控件(Car),然后沿着UI元素的Info属性向下移动到其内容的MaxSpeed属性


正如我在评论中所说的,将UI元素与数据元素紧密匹配,然后将数据对象分配给UI元素上相对非标准的属性,这将使问题变得非常棘手。您可能有自己的理由,但XAML和WPF不需要那么复杂。

这段代码对我来说很好:

<TextBlock Text="{Binding Path=Info.MaxSpeed, RelativeSource={RelativeSource Mode=TemplatedParent}}" />

好吧,说实话,我知道如何使用DataContext解决这个问题。但我希望我可以在没有DataContext的情况下做到这一点,因为实际上,如果我使用DataContext,我并不需要创建CarInfo:Info属性。因此,如果我正在编写Car.DataContext=new CarInfo{MaxSpeed=100},那么我的简单代码工作得很好。但我希望代码也能正常工作:Car.Info=new CarInfo{MaxSpeed=100}@AlexanderKnoth您需要清楚地回答您的问题。。。如果您不想使用DataContext,那么您想使用什么?元素绑定?看起来你真的把自己弄得一团糟,而且你的UI与你的数据项如此精确地匹配并没有让你变得更容易。如果我写:Car.Info=new CarInfo{MaxSpeed=100}它不起作用:(尝试添加Mode=TwoWay;Thx到all寻求帮助,我找到了答案,我已经在下面发布了。)
<TextBlock Text="{Binding Path=Info.MaxSpeed, RelativeSource={RelativeSource Mode=TemplatedParent}}" />
Car.Info = new CarInfo { MaxSpeed = 100.0 };