2012-05-10 89 views
4

我有一個從Window派生的簡單視圖。在該派生類的文件後面的代碼中,我定義了一個名爲ActiveDocument的新DependencyProperty。綁定到XAML派生類中定義的依賴項屬性

我希望將這個新的DependencyProperty綁定到ViewModel上的一個屬性,該屬性被設置爲視圖的DataContext。

我可以使用類構造函數中的代碼設置此綁定,但嘗試綁定XAML文件中的屬性會導致出現錯誤消息,指出在類Window上找不到屬性ActiveDocument。

在XAML中這樣做的正確語法是什麼?

[用代碼更新]

MainWindowViewModel.cs

class MainWindowViewModel 
{ 
    public bool IWantBool { get; set; } 
} 

MainWindow.xaml.cs

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     DataContext = new MainWindowViewModel(); 
     InitializeComponent(); 
    } 

    public static readonly DependencyProperty BoolProperty = DependencyProperty.Register(
     "BoolProperty", typeof(bool), typeof(MainWindow)); 
} 

Mainwindow.xaml

<Window x:Class="DependencyPropertyTest.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:DependencyPropertyTest" 

    <!-- ERROR: BoolProperty not found on type Window. --> 
    BoolProperty="{Binding path=IWantBool}" 

    <!-- ERROR: Attachable property not found in type MainWindow. --> 
    local:MainWindow.BoolProperty="{Binding path=IWantBool}"> 

    <Grid> 

    </Grid> 
</Window> 
+0

請問您可以發佈代碼嗎?看起來你的XAML缺少'x:Class'屬性。 – Vlad

回答

2

XAML編譯器不考慮Window的實際類型,它僅查看根元素的類型。所以它不知道在MainWindow中聲明的屬性。我不認爲你可以在XAML中輕鬆做到這一點,但在代碼隱藏方面很容易:

public MainWindow() 
{ 
    DataContext = new MainWindowViewModel(); 
    InitializeComponent(); 
    SetBinding(BoolProperty, new Binding("IWantBool")); 
}