What's wrong with my WPF Binding (in C# code)?

I didnt use WPF for a long time so I'm quite sure this is an easy question for most of you but here is my xaml code :

<Grid>
    <ProgressBar Name="Progress" Width="200" Height="20" Minimum="0" Maximum="100" Margin="10"/>
</Grid>

and here is the C# code :

namespace WpfApplication1
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private int _MyInt;
        public int MyInt
        {
            get { return _MyInt; }
            set
            {
                _MyInt = value;
                RaisePropertyChanged("MyInt");
            }
        }

        public MainWindow()
        {
            InitializeComponent();

            MyInt = 99;

            Random random = new Random();
            System.Timers.Timer aTimer = new System.Timers.Timer();
            aTimer.Elapsed += (sender, e) =>
            {
                MyInt = random.Next(0, 100);
            };
            aTimer.Interval = 500;
            aTimer.Enabled = true;

            Binding b = new Binding();
            b.Source = MyInt;
            b.Mode = BindingMode.OneWay;
            Progress.SetBinding(ProgressBar.ValueProperty, b);
        }
        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

When the application starts I got a 99 value on my ProgressBar so the binding seems to work but then, it doesn't refresh at all...

Answers


Progress.Value = MyInt is simply setting the value to whatever the current value in MyInt is. This is not the same as binding the value, which means the value will point to MyInt, not be a copy of MyInt

To create a binding in the code-behind, it would look something like this:

Binding b = new Binding();
b.Source = this;
b.Path = new PropertyPath("MyInt");
Progress.SetBinding(ProgressBar.ValueProperty, b);

An alternative is to just bind the value in your XAML and update it as needed:

<ProgressBar Name="Progress" Value="{Binding MyInt}" />

Then in the code behind: MyInt = newValue;


Need Your Help

Catmull Rom Spline implementation (LibGDX)

java android libgdx catmull-rom-curve

I want to generate a random spline across my screen.

Cleaning out test database before running tests

node.js express mocha sequelize.js

What is the best way to clean out a database before running a test suite (is there a npm library or recommended method of doing this).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.