我遇到了與父MainWindow屬性MainContentVisibility綁定的問題。我有以下代碼:WPF:綁定到MainWindow屬性
MainWindow.xaml
<Window x:Class="CallTracker.WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:v="clr-namespace:MyProgram.WPF.Views"
DataContext="{Binding MainPageViewModel, Source={StaticResource Locator}}">
<StackPanel>
<v:CompanyInfoUserControl Width="800" Visibility="{Binding MainContentVisibility, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" />
<v:MainContentUserControl Width="800" Visibility="{Binding Path=MainContentVisibility, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" />
</StackPanel>
</Window>
目前我的兩個用戶控件只不過是用一個文本塊堆面板的更多,直到我找出這個問題的可見性。
我可以使用snoop來檢查我的MainPageViewModel,我可以看到屬性MainContentVisibilty設置爲「摺疊」,但CompanyInfoUserControl顯示了其知名度的問題結合:
System.Windows.Data Error: 40 : BindingExpression path error: 'MainContentVisibility' property not found on 'object' ''MainWindow' (Name='')'. BindingExpression:Path=MainContentVisibility; DataItem='MainWindow' (Name=''); target element is 'CompanyInfoUserControl' (Name=''); target property is 'Visibility' (type 'Visibility')
有人能解釋我是什麼在這裏做錯了嗎?
編輯
我想保羅的建議,現在我得到這個作爲綁定錯誤從窺探:
System.Windows.Data Error: 40 : BindingExpression path error: 'MainContentVisibility' property not found on 'object' ''MainPageViewModel' (HashCode=63642613)'. BindingExpression:Path=MainContentVisibility; DataItem='MainPageViewModel' (HashCode=63642613); target element is 'CompanyInfoUserControl' (Name=''); target property is 'Visibility' (type 'Visibility')
SOLUTION
我本來就不是綁定到我的數據模型,而是XAML對象(在本例中爲MainWindow.xaml)爲了綁定到數據,我必須添加引用'DataContext',如下所示:
<v:CompanyInfoUserControl Visibility="{Binding DataContext.MainContentVisibility, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" />
訪問它,你可以點擊接受剔提供一個名稱對於其中一個答案(相對於在問題標題中加入已解決的問題) – 2016-06-02 14:14:01