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

点点圈 提交于 2019-12-24 08:57:59

问题


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


回答1:


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;




回答2:


First, I don't think your window should be implementing the INotifyPropertyChanged. You are putting the data in your Window. You should have a separate class that implements INotifyPropertyChanged, and then set it as a DataContext to your Window. After that you need to add a Binding either through code, or in XAml like this :

<ProgressBar Name="Progress" Width="200" Height="20" Minimum="0" Maximum="100" Margin="10" Value="67" Value="{Binding MyInt}"/>


来源:https://stackoverflow.com/questions/8342941/whats-wrong-with-my-wpf-binding-in-c-sharp-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!