【问题标题】:Bind to dependency property defined in derived class in XAML绑定到 XAML 派生类中定义的依赖属性
【发布时间】:2012-05-19 00:11:03
【问题描述】:

我有一个从 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 缺少 x:Class 属性。

标签: c# wpf xaml


【解决方案1】:

XAML 编译器不考虑Window 的实际类型,它只查看根元素的类型。所以它不知道MainWindow 中声明的属性。我不认为你可以在 XAML 中轻松地做到这一点,但在代码隐藏中很容易做到:

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

【讨论】:

    猜你喜欢
    • 2011-12-20
    • 2017-12-18
    • 2011-06-25
    • 2014-01-09
    • 2023-03-13
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 2013-10-16
    相关资源
    最近更新 更多