簡體   English   中英

使用MVVM的WPF:使用RelativeSource的DataBinding

[英]WPF using MVVM: DataBinding with RelativeSource

我有一個控件,在該控件中我有一個帶有數據tempalte的資源:

  <DataTemplate DataType="{x:Type local:FlowModel}">
    <Image Source="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vm:MainViewModel}}, Path=MainViewModel.ImagePath}"/>
  </DataTemplate>

 xmlns:vm="clr-namespace:CortexMonitoringTool.ViewModel"

我將vm設置為我的ViewModel文件夾,我正在實現mvvm。 我不能讓我的約束力工作,我不確定為什么不。

有人可以告訴我,如果我的相對綁定是正確的,它是否可以在我的MainViewModel類中實際看到我的屬性'ImagePath'?

public String ImagePath
    {
        get
        {
            return _imagePath;
        }
        set
        {
            if (_imagePath == value)
            {
                return;
            }
            _imagePath = value;
            RaisePropertyChanged("ImagePath");
        }
    }

謝謝。

嗨,我設法讓它工作。

  <DataTemplate DataType="{x:Type local:FlowModel}">
    <Image Source="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.ImagePath}"/>
  </DataTemplate>

我將AncestorType改為'Window',它已經准備好綁定到我的MainViewModel,然后使用'DataContext'。 在我的路徑中能夠看到我的財產。

希望這有助於其他人!!

您查看模型不是Visual樹的一部分。 所以找到祖先類型不會在那里工作。 如果您找到具有datacontext的根父級,則可以使用其屬性與like綁定。

<Image Source={...... Path=DataContext.MyProperty}"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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