2013-03-10 19 views
1

執行以下操作有沒有簡單的方法?指定多個RelativeSource.AncestorTypes

<Binding RelativeSource="{RelativeSource AncestorType=UserControl OR Window}" Path="Tag" /> 

我只想綁定到頂級父級的Tag屬性,它可以是UserControl或Window。但請注意,從當前控件到父項的距離是任意的,所以我不能使用AncestorLevel

+0

沒有理由列出的標籤在你的問題標題。請參閱http:/ /meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles討論爲什麼不需要。 – Patrick 2013-03-10 17:19:42

+0

另外,類似stukselbax迴應你的[其他問題](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles)寫你可能可以解決這個問題帶有標記擴展,或者帶有一些值轉換器。你嘗試過嗎? – Patrick 2013-03-10 17:21:06

+0

@帕特里克:感謝代碼使用建議。這很有道理。至於stukselbax的回答(您可能想要更正您評論中的鏈接),這一點對我而言非常複雜。正如你在Phil的回答中看到的那樣,解決方案要簡單得多。 – dotNET 2013-03-11 03:26:54

回答

3

那麼,如果這是你想要:)

public partial class MainWindow : ITopLevel 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 

     Tag = "I'm at the top"; 
    } 
} 

public interface ITopLevel 
{ 
    // optionally specify Tag in the interface, it will work either way 
    object Tag { get; set; } 
} 

<Grid> 
    <Button Content="{Binding Path=Tag, RelativeSource={RelativeSource 
      FindAncestor, AncestorType={x:Type Demo:ITopLevel}}}"/> 
</Grid> 
+0

嗯,這是一個有趣的方法!目前我通過使用MainWindowViewModel和我需要的東西來解決這個問題。我在xaml中使用FindAncestor Window綁定,或者使用IoC將MainWindowViewModel傳遞給孩子,並訪問我需要的方式。 – failedprogramming 2013-03-10 22:22:55

+0

@菲爾:完美。想知道爲什麼在這個世界上我沒有想出這個簡單的想法。 – dotNET 2013-03-11 03:20:04

0

一個黑客可以只使用MultiBinding代替Binding這個,然後做一個簡單的IMultiValueConverter是發現在「值」的第一個項目,是不是空(或DependencyProperty.UnsetValue,與Visual樹工作時往往會彈出。

這是要做到這一點少哈克的方式,和完美的作品對我來說。