如何绑定到依赖对象的依赖属性?

问题描述 投票:0回答:1

以下只是对问题核心的总结。

我定义了有一个依赖属性的类如下。

public class TestMap : DependencyObject
{
    public bool TestProperty
    {
        get { return (bool)GetValue(TestPropertyProperty); }
        set { SetValue(TestPropertyProperty, value); }
    }

    public static readonly DependencyProperty TestPropertyProperty =
        DependencyProperty.Register("TestProperty", typeof(bool), typeof(TestMap), new PropertyMetadata(false));
}

现在我准备在UserControl.下面的代码就是一个例子。

public class UserControl1 : Control
{
    public TestMap TestMap { get; set; }
}

我在MainWindow中使用了UserControl1,如下图所示。

<Window>
    <Grid>
        <local:UserControl1 />
    </Grid>
</Window>

上面的代码工作得很好,但是如果我试着绑定TestMap.TestProperty,我应该怎么做呢,我试了下面的代码,但是没有用。(假设ViewModel已绑定)

<Window>
    <Grid>
        <local:UserControl1 TestMap.TestProperty="{Binding ViewModelProperty}"/>
    </Grid>
</Window>

上述代码的错误信息如下图所示。

enter image description here

错误信息是 "It can't find connectable 'TestProperty' property in the 'TestMap' format"。

感谢您的阅读。

wpf binding dependency-properties
1个回答
0
投票

你不能绑定到一个嵌套的属性,即一个属性 TestProperty 属性返回的对象的 TestMap,像这样的XAML。这是不支持的。

你应该把 TestPropertyUserControl,以程序方式设置,或考虑使用一个 依附属性 可在任何特定类型的对象上设置。

© www.soinside.com 2019 - 2024. All rights reserved.