【问题标题】:WPF how to update UI while runtimeWPF如何在运行时更新UI
【发布时间】:2015-10-24 11:50:46
【问题描述】:

好的, 我的问题如下:

我有一个显示画布的 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);
        }

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

我怎么能意识到这一点?

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

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

【问题讨论】:

标签: c# wpf canvas visualization


【解决方案1】:

属性必须调用来自INotifyPropertyChanged 接口的PropertyChanged 事件才能使绑定工作。这是实现这一目标的最快方法。

在代码后面

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>

【讨论】:

    猜你喜欢
    • 2013-09-14
    • 1970-01-01
    • 2014-11-25
    • 2018-06-10
    • 2011-01-18
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多