这有什么错我的WPF绑定(在C#$ C $三)? [英] What's wrong with my WPF Binding (in C# code)?

查看:92
本文介绍了这有什么错我的WPF绑定(在C#$ C $三)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有使用WPF很长一段时间,所以我敢肯定这是你最简单的问题,但这里是我的XAML 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>

和这里是C#code:

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

在应用程序启动时我得到了99值在我的进度如此的结合似乎工作但后来,它不会刷新在所有...

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

推荐答案

Progress.Value =敏被简单地设置在价值无论当前值是。这是不一样的绑定值,这意味着该值将指向,不是敏的副本

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

要创建在$ C $绑定C-的背后,它会是这个样子:

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

另一种方法是只绑定在你的XAML的价值,并根据需要更新:

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

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

然后在后面的code:敏=为newValue;

这篇关于这有什么错我的WPF绑定(在C#$ C $三)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆