gpt4 book ai didi

c# - WPF 如何在运行时更新 UI

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

好的,我的问题如下:

我有一个显示 Canvas 的 UI,其中有许多黑色圆圈和一个红色圆圈

所以:如果我按下“开始”按钮,我的代码将红色圆圈向右移动 10 次。在逻辑中,我计算每次移动后的所有交叉点。所以我计算了 10 次。但现在我想在每次移动后更新 UI 并显示交叉点。

这里是代码示例

        for(int i = 0; i < 10; i++)
{
rc.xValue += 20;
calculateIntersections();
//now here the UI should be updated
Thread.Sleep(1000);
}

所以我会从逻辑中的计算中得到一个“可视化”。

我如何实现这一点?

我不能使用绑定(bind)(或者我不知道其他方法)的问题是,使用绑定(bind)后我只能看到我移动的最后一步。所以我会在向右移动 200 后看到红色圆圈......但我想看到每一步。

我试过的。我计算了步数,并在每次单击按钮时增加了步数。但这并不舒服。我希望这就像一部“电影”,而不是每次都点击。而且使用许多“foreach”比使用许多“计数器”要容易得多。

最佳答案

属性必须调用来自 INotifyPropertyChanged 接口(interface)的 PropertyChanged 事件才能进行绑定(bind)。这是实现该目标的最快方法。

在代码后面

public partial class MainWindow : Window, INotifyPropertyChanged
{
private double _rcXValue;
public double RcXValue
{
get { return _rcXValue; }
set
{
_rcXValue = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("RcXValue"));
}
}

public MainWindow()
{
InitializeComponent();
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 10; i++)
{
RcXValue += 20; //UI should be updated automatically
calculateIntersections();
await Task.Delay(1000);
}
}

public event PropertyChangedEventHandler PropertyChanged;
}

在 XAML 中

<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="260*"/>
<RowDefinition Height="59*"/>
</Grid.RowDefinitions>
<Canvas>
<Ellipse Fill="Red" Height="17" Canvas.Left="{Binding RcXValue}" Stroke="Black" Canvas.Top="107" Width="17"/>
</Canvas>
<Button Content="Button" Grid.Row="1" Click="Button_Click"/>
</Grid>
</Grid>
</Window>

关于c# - WPF 如何在运行时更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33317854/

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