我的WPF绑定(在c#代码中)有什么问题?
本文关键字:什么 问题 代码 绑定 WPF 我的 | 更新日期: 2023-09-27 18:16:26
我没有使用WPF很长一段时间,所以我很确定这是一个简单的问题,但这是我的xaml代码:
<Grid>
<ProgressBar Name="Progress" Width="200" Height="20" Minimum="0" Maximum="100" Margin="10"/>
</Grid>
,这里是c#代码:
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));
}
}
}
当应用程序启动时,我的ProgressBar上的值是99,所以绑定似乎有效,但随后,它根本不刷新…
Progress.Value = MyInt
只是将值设置为MyInt
中的当前值。这与绑定值不同,这意味着该值将指向MyInt
,而不是MyInt
的副本
Binding b = new Binding();
b.Source = this;
b.Path = new PropertyPath("MyInt");
Progress.SetBinding(ProgressBar.ValueProperty, b);
另一种方法是在XAML中绑定该值,并根据需要更新它:
<ProgressBar Name="Progress" Value="{Binding MyInt}" />
然后在后面的代码中:MyInt = newValue;
首先,我不认为你的窗口应该实现INotifyPropertyChanged
。您正在将数据放入窗口中。你应该有一个单独的类来实现INotifyPropertyChanged
,然后将它设置为Window的DataContext。之后,您需要通过代码或在XAml中添加Binding,如下所示:
<ProgressBar Name="Progress" Width="200" Height="20" Minimum="0" Maximum="100" Margin="10" Value="67" Value="{Binding MyInt}"/>