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

标签 c# wpf canvas visualization

好的, 我的问题如下:

我有一个显示 Canvas 的用户界面,其中有许多黑色圆圈和一个红色圆圈

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

这里是一个代码示例

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

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

我怎样才能实现这一点?

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

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

最佳答案

属性必须调用来自 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/

相关文章:

c# - Entity Framework core 2.0.3 未提供数据库中的最新数据

c# - 事件在错误的线程中?

具有弯曲边缘的Android矩形

c# - 在 C# 中将参数传递给变量的更短方法?

c# - 看不懂这个斐波那契程序流程

c# - GridView 或 DataGrid 项目的可编辑列表

wpf - 如何在 xaml 字符串中使用 "{"符号

javascript - 在 d3 Canvas map 上绘制圆弧时出现问题

linux - SWT Canvas 在 Windows 上无法重绘,但在 Linux 上可以正常工作

c# - 由于 appsettings.json 的路径,添加迁移无法从文件 appsettings.json 读取连接字符串