J.Green
J.Green

Reputation: 51

Fail to bind in WPF

I'm now studying binding in WPF.
I wanna bind Button.IsEnabled Property to Property of Class1; Button.IsEnabled=c1.Property. In fact, Textblock.Text changes as I intended but Button.IsEnabled doesn't.
Here is my code:

[MainWindow.xaml.cs]

using System.Windows;

namespace WpfApp2
{
    public partial class MainWindow : Window
    {
        public static Class1 c1 { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            c1 = new Class1();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            c1.Property = !c1.Property;
            textblock.Text = c1.Property.ToString();
        }
    }
}

[MainWindow.xaml]

<Window x:Class="WpfApp2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" Margin="150,137,0,0" VerticalAlignment="Top" Width="75" IsEnabled="{Binding Property, Source={x:Static local:MainWindow.c1}}"/>
        <Button Content="Button2" HorizontalAlignment="Left" Margin="271,137,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
        <TextBlock x:Name="textblock" HorizontalAlignment="Left" Margin="150,177,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
    </Grid>
</Window>

[Class1.cs]

namespace WpfApp2
{
    public class Class1
    {
        public bool Property { get; set; }
    }
}

What's wrong? I can't guess... Can I do it only in code? Please help me!

Upvotes: 2

Views: 101

Answers (1)

vasily.sib
vasily.sib

Reputation: 4002

You need to implement the INotifyPropertyChanged interface in your Class1 and raise its PropertyChanged event when the Property value changes:

namespace WpfApp2
{
    public class Class1 : INotifyPropertyChanged
    {
        private bool property = false;

        public bool Property
        {
            get { return property; }
            set { if (value != property) { property = value; RaisePropertyChanged(); } }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
            => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName);
    }
}

Upvotes: 3

Related Questions