簡體   English   中英

WPF綁定到其他類的非簡單屬性的屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM