代码之家  ›  专栏  ›  技术社区  ›  zxcvbnm

wpf:绑定到自定义类“找不到绑定源”

  •  0
  • zxcvbnm  · 技术社区  · 16 年前

    是这样做的:

    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 回复  |  直到 16 年前
        1
  •  2
  •   Rory    16 年前

    ElementName Binding myClass DataContext

    public partial class Window1 : Window
    {
        //myClass test;
    
        public Window1()
        {
            InitializeComponent();
            this.DataContext = new myClass(); //test = new myClass();
        }
    }
    

    IsEnabled="{Binding Path=MyFlag}"

    IsEnabled="{Binding RelativeSource={RelativeSource Self}, Path=test.MyFlag}"