5
votes

I have a simple view derived from Window. In the code behind file for that derived class I define a new DependencyProperty called ActiveDocument.

I wish to bind this new DependencyProperty to a property on the ViewModel which is set as the view's DataContext.

I can set this binding using code in the classes constructor, but attempting to bind the property in the XAML file causes an error message saying that the property ActiveDocument cannot be found on class Window.

What is the correct syntax for doing this in XAML?

[Update with code]

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>
1
Could you please post the code? Look like your XAML is missing x:Class attribute.Vlad

1 Answers

3
votes

The XAML compiler doesn't consider the actual type of the Window, it only looks at the type of the root element. So it's not aware of properties declared in MainWindow. I don't think you can easily do it in XAML, but it's easy to do in code-behind:

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