Bind to dependency property defined in a derived class in XAML

I have a simple view obtained from a window. In the code file for this derived class, I define a new DependencyProperty called ActiveDocument.

I want to bind this new DependencyProperty to a property in the ViewModel that is set as the DataContext view.

I can set this binding using the code in the class constructor, but trying to bind a property in the XAML file throws an error message indicating that the ActiveDocument property cannot be found in the class window.

What is the correct syntax for 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>
+5
source share
1 answer

XAML Window, . , MainWindow. , XAML, :

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

All Articles