gpt4 book ai didi

c# - WPF 在 for 循环中递增绑定(bind)属性不会通知 UI 并阻止它

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:42 25 4
gpt4 key购买 nike

我在使用 wpf 和 mvvm 时遇到了非常奇怪的问题。假设您有一个 textbox 绑定(bind)到 View 模型上的 Counter 属性。按钮更改 View 模型的属性,这会引发 PropertyChanged 事件并更新 UI。好吧,如果我做类似 Counter++ 的事情,这正是正在发生的事情但是,当我尝试在 for 循环中这样做时,一次单击更改 Counter 属性 10 次,它阻止 UI 并在循环结束时仅显示最后一个字符串。这是代码:

public class MainViewModel : INotifyPropertyChanged
{
private int counter;

public int Counter
{
get { return counter; }
set { counter = value; Notify("Counter"); }
}

public MainViewModel()
{
Counter = 0;
}

public void inc()
{
for (int i = 0; i < 10000; i++)
{
Counter++;
}
}

public event PropertyChangedEventHandler PropertyChanged;

public void Notify(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void button_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var dataContext = button.DataContext as MainViewModel;
dataContext.inc();
}
}



<Window x:Class="WpfTests.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:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:i="http://schemas.microsoft.com/prototyping/2010/interactivity"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfTests"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainViewModel></local:MainViewModel>
</Window.DataContext>
<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="40,106,0,0" TextWrapping="Wrap" Text="{Binding Counter}" VerticalAlignment="Top" Width="120"/>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="287,106,0,0" VerticalAlignment="Top" Width="75" Click="button_Click">

</Button>

</Grid>

最佳答案

Well, that is exactly what's happening if i do something like Counter++ But, when i try to do that in for loop, to change Counter property 10 times on one click, it blocks UI and display just last string at the end of the loop.

当您更改 Counter 属性时,您是在 UI 线程中进行的。在此期间,UI 线程被阻塞。第一次更改完成后,您将再次更新 Counter 属性 => UI 线程再次被阻塞。

所以这正是我们所期望的。

关于c# - WPF 在 for 循环中递增绑定(bind)属性不会通知 UI 并阻止它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32027328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com