我有一个从Window派生的简单视图.在该派生类的代码隐藏文件中,我定义了一个名为ActiveDocument的新DependencyProperty.
我希望将这个新的DependencyProperty绑定到ViewModel上的一个属性,该属性被设置为视图的DataContext.
我可以使用类构造函数中的代码设置此绑定,但是尝试绑定XAML文件中的属性会导致出现错误消息,指出无法在类Window上找到属性ActiveDocument.
在XAML中执行此操作的正确语法是什么?
[使用代码更新]
MainWindowViewModel.cs
class MainWindowViewModel
{
public bool IWantBool { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
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));
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
XAML 编译器不考虑 的实际类型Window,它只查看根元素的类型。所以它不知道 中声明的属性MainWindow。我不认为你可以在 XAML 中轻松做到这一点,但在代码隐藏中很容易做到:
public MainWindow()
{
DataContext = new MainWindowViewModel();
InitializeComponent();
SetBinding(BoolProperty, new Binding("IWantBool"));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1301 次 |
| 最近记录: |