WPF:绑定到自定义类“无法找到绑定源”

时间:2010-02-17 05:45:35

标签: wpf data-binding

这样做了:

public class myClass : INotifyPropertyChanged
{
    public bool? myFlag = false;
    public bool? MyFlag
    {
        get { return myFlag; }
        set
        {
            myFlag = value;
            OnPropertyChanged("MyFlag");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

在Window1类中声明了一个测试变量myClass:

public partial class Window1 : Window
{
    myClass test;

    public Window1()
    {
        InitializeComponent();
        test = new myClass();
    }
}

以下是一个示例XAML文件:

<Window x:Class="WpfApplication5.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300" IsEnabled="{Binding ElementName=test, Path=MyFlag}">
    <Grid>
        <Button>You shouldn't be clicking me</Button>
    </Grid>
</Window>

窗口未被禁用,调试器正在向我显示该消息。

我错过了什么?

1 个答案:

答案 0 :(得分:2)

ElementName的{​​{1}}属性旨在定位xaml中的其他元素,而不是对象的属性/字段。执行您要完成的任务的常用方法是将Binding的实例分配给Window的myClass属性:

DataContext

然后您的绑定将如下所示:public partial class Window1 : Window { //myClass test; public Window1() { InitializeComponent(); this.DataContext = new myClass(); //test = new myClass(); } }

如果你真的想要绑定到Window本身的属性,你可以使用这样的绑定: IsEnabled="{Binding Path=MyFlag}"

相关问题