views:

25

answers:

1

Did this:

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));
    }
}

Declared a test variable myClass in the Window1 class:

public partial class Window1 : Window
{
    myClass test;

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

Here's an example XAML file:

<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>

The window isn't disabled, and the debugger is showing me that message.

What am I missing?

+2  A: 

The ElementName property of the Binding is meant to target other elements in xaml, not properties/fields of the object. The common way to do what you're trying to accomplish is to assign an instance of myClass to the Window's DataContext property:

public partial class Window1 : Window
{
    //myClass test;

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

And then your binding will look like this: IsEnabled="{Binding Path=MyFlag}".

If you actually wanted to bind to a property on the Window itself, you would use a binding like this: IsEnabled="{Binding RelativeSource={RelativeSource Self}, Path=test.MyFlag}"

Rory
Is there a way to do this using XAML? Also, what if I want to access that MyFlag later in code to change it?
zxcvbnm
Picky point on your final para: if he goes this route, he'll also need to convert test to a property instead of a field, because WPF data binding considers only properties. But your first suggestion is definitely the better one, and if he takes your advice, that latter problem doesn't arise.
itowlson
@itowlson: Good point, I'd actually forgotten about that. I just wanted to give him a way to do what he tried in the question.@zxcvbnm: Damn, that's a hard name to type. If you wanted to set the DataContext from xaml, you could use an attached behavior (http://www.google.com/search?q=attached+behavior) to do it. Normally its done using the MVVM pattern (a lot of the frameworks available for the pattern have some method of doing it for you, http://wpfonyx.codeplex.com/ for example).
Rory