我刚开始使用Caliburn Micro并试图绕过IResult。为此,我写了一些虚拟代码。代码用于在文本框中显示“正在加载...”,直到完成一些冗长的操作(Task.Delay),此时文本应该消失。这是我的代码:
视图模型:
[Export(typeof(IShell))]
public class ShellViewModel : IShell
{
public string MyMessage { get; set; }
public IEnumerable<IResult> DoSomething()
{
yield return Loader.Show("Loading...");
yield return Task.Delay(1000).AsResult();
yield return Loader.Hide();
}
}
查看:
<Window x:Class="CaliburnMicroTest.ShellView"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:CaliburnMicroTest"
xmlns:cal="http://www.caliburnproject.org"
mc:Ignorable="d"
Title="ShellView" Height="300" Width="300">
<StackPanel>
<Button Content="Do Something"
x:Name="DoSomething" />
<TextBox Text="{Binding Path=MyMessage, Mode=TwoWay}"/>
</StackPanel>
</Window>
Loader class:
public class Loader : IResult
{
readonly string message;
readonly bool hide;
public Loader(string message)
{
this.message = message;
}
public Loader(bool hide)
{
this.hide = hide;
}
public event EventHandler<ResultCompletionEventArgs> Completed;
public void Execute(CoroutineExecutionContext context)
{
var target = context.Target as ShellViewModel;
target.MyMessage = hide ? string.Empty : message;
Completed(this, new ResultCompletionEventArgs());
}
public static IResult Show(string message = null)
{
return new Loader(message);
}
public static IResult Hide()
{
return new Loader(true);
}
}
当我点击按钮时,我希望文本框中填充“加载...”一秒钟,然后再次变为空,但文本框中没有任何内容显示。另外,在我调试时,我的ViewModel上的MyMessage属性的值为“Loading ...”。为什么文字没有显示在我的视图上?
答案 0 :(得分:1)
您的视图模型类应继承自PropertyChangedBase
并提出更改通知:
[Export(typeof(IShell))]
public class ShellViewModel : IShell, PropertyChangedBase
{
string _myMessage;
public string MyMessage
{
get { return _myMessage; }
set
{
_myMessage = value;
NotifyOfPropertyChange(() => MyMessage);
}
}
public IEnumerable<IResult> DoSomething()
{
yield return Loader.Show("Loading...");
yield return Task.Delay(1000).AsResult();
yield return Loader.Hide();
}
}