![](/img/trans.png)
[英]Is derived type also becomes owner for dependency property defined in base class (in WPF/XAML)
[英]Bind to dependency property defined in derived class in XAML
我有一个从Window派生的简单视图。 在该派生类的代码隐藏文件中,我定义了一个名为ActiveDocument的新DependencyProperty。
我希望将这个新的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>
XAML编译器不考虑Window
的实际类型,它只查看根元素的类型。 所以它不知道在MainWindow
声明的属性。 我不认为你可以轻松地在XAML中做到这一点,但在代码隐藏中很容易做到:
public MainWindow()
{
DataContext = new MainWindowViewModel();
InitializeComponent();
SetBinding(BoolProperty, new Binding("IWantBool"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.