2010-07-26 73 views
0

我正在創建一個wpf應用程序,並且在實現用戶界面想法時遇到了一些困難。綁定到datacontext之外的屬性

我有一個MasterViewModel綁定到MainWindow,它暴露了可觀察的ViewModel集合。我已經編寫了一些基本上在可觀察集合中切換當前視圖模型的命令,並隨後顯示相應的視圖。但是,當應用程序第一次加載時,我將HomeViewModel添加到顯示主頁(導航)視圖的集合中。我遇到的問題是我綁定的命令在MasterViewModel上暴露,因此它們不是'級聯'到項目控件中。任何人都可以提供一個解決方案或更好的?非常感謝。

這是我收到錯誤:

System.Windows.Data錯誤:40:BindingExpression路徑錯誤:對 '對象' '' HomeViewModel」未找到 'MainWindowViewModel' 屬性(的HashCode = 5313339) 」。 BindingExpression:路徑= MainWindowViewModel.LoadClientsCommand; DataItem ='HomeViewModel'(HashCode = 5313339);目標元素是'Button'(Name ='');目標屬性是'命令'(類型'ICommand')

回答

2

我相信你可以通過的RelativeSource您MasterViewModel的DataContext的訪問命令,以下列方式:

<Button> 
    <Button.Command> 
     <Binding Path="DataContext.MasterViewCommand"> 
      <Binding.RelativeSource> 
       <RelativeSource 
        Mode="FindAncestor" 
        AncestorType="{x:Type MasterViewBaseClass}" 
       /> 
      </Binding.RelativeSource> 
     </Binding> 
    </Button.Command> 
    Click me! 
</Button> 
1

你能提供你的代碼場景的代碼示例嗎?

  1. 這讓我想起Josh Smith的MVVM示例(http://msdn.microsoft.com/en-us/magazine/dd419663.aspx),mb您從那裏獲得了您的想法?
  2. 如果我正確理解你:你爲什麼不爲你的ItemControl編寫一個虛擬機,並把你的命令放在那裏?
  3. 你可以嘗試通過的RelativeSource從ItemControl訪問的命令(How do I use WPF bindings with RelativeSource?
+0

呀我試圖從這裏適應我的想法,但唯一的問題是到達用戶控制之外以獲取命令。 – aligray 2010-07-26 10:05:00

相關問題