简体   繁体   中英

Bind to dependency property defined in derived class in XAML

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>

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"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM