【问题标题】:Correct and proper binding of a control/UIElement visibility to Property MVVM C# WPF将控件/UIElement 可见性正确且正确地绑定到 Property MVVM C#​​ WPF
【发布时间】:2013-06-09 17:04:17
【问题描述】:

我对 MVVM 很陌生,我一直在构建我的 ViewModel。我有一个包含ICommand 的 ViewModel,然后通过命令按钮将其绑定到我的视图中。 ICommand 导致在我的 ViewModel 上调用一个过程,然后调用一个更大的慢速过程。在此过程发生时,我想让控件/UIElement 的可见性变为可见,然后在过程完成后隐藏(我打算绑定标签并不确定进度条的可见性)

例如,在我的视图模型中,我有

public void calledFromCommandButton() {
RaisePropertyChange("Starting");
superLongProcedure();
RaisePropertyChange("Finished");

}

这只是感觉有点傻,不得不提出 2 个不同的属性更改,因此,我认为我做错了。我想我可以通过一个属性更改和一个转换器来做到这一点?

那么,将 UIElement 可见性绑定到属性更改事件的正确和正确方法是什么?

谢谢 托马斯

【问题讨论】:

  • “Starting”和“Finished”属性有什么用?有一个 bool 属性 IsBusy 然后你可以使用 Visibility="{Binding Path=IsBusy, Converter={StaticResource bool2VisibilityConverter}}"

标签: c# wpf mvvm binding viewmodel


【解决方案1】:

我建议使用单个boolean 属性(IsWorking 或其他),然后使用BooleanToVisibilityConverter 显示和隐藏按钮。所以,它看起来像:

<Window ...>
    <Window.Resources>
       <BooleanToVisibilityConverter x:Key="TrueToVisibleConverter"/>
    </Window.Resources>
     ...
    <Button x:Name="CancelButton" Content="Cancel" Visiblity="{Binding IsWorking, Converter={StaticResource TrueToVisibleConverter}}"/>
     ...
</Window/>

【讨论】:

  • 所以你的意思是有类似_bIsBusy = true; PropertyHasChanged("IsBusy"); DO CALCULATION _bIsBusy = false; PropertyHasChanged("IsBusy"); Then have public Visibility IsBusy { get { return _bIsBusy ? Visibility.Visible : Visibility.Hidden; } } 的东西,问题是,UI 不会更新,直到计算完成,此时控件再次不可见。有任何想法吗?谢谢
  • 您不想使用BackgroundWorker,还是不想在后台线程上工作?如果您不打算在后台线程上执行工作,那么 UI 将在工作完成之前永远不会更新,因为 UI 线程将被阻塞。没办法。如果您只是不想使用BackgroundWorker,可以使用异步执行工作的替代方法 - 如果您使用 >= .NET 4,请查看 Task。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-06
  • 1970-01-01
相关资源
最近更新 更多