Caliburn Micro-使用IRESULT和呈现视图



我刚开始使用Caliburn Micro,并试图将我的头缠绕在Iresult上。为此,我写了一些虚拟代码。该代码旨在在文本框中显示"加载...",直到完成一些冗长的操作(Task.delay(完成,此时文本应消失。这是我的代码:

ViewModel:

[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>

加载程序类:

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属性具有"加载..."的值。为什么文本不在我的视图上显示?

您的视图模型类应从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();
    }
}

相关内容

  • 没有找到相关文章

最新更新