使用MVVM模式在WPF中传输数据



我陷入困境太久了,我只需要有人给我指明方向。。。

问题是,我试图使用MVVM模式进行开发,但我似乎不知道如何从方法中传输一些数据并将其绑定到XAML。此外,我在所有这些结构中设置接口(INotifyPropertyChanged)时也遇到了问题。你们中有谁能说明它必须在哪里实现吗?

我会试着解释我的代码。。。

我有一个数据模型,例如,将是一个API,它将从web获取一些数据:

public class DataModel
{
    public string apiResult = "null";
    private void GetDataFromApi()
    {
        // Some web service
        apiResult = "SOME RESULT FROM WEB API";
    }
}

现在我有了一个逻辑的ViewModel:

public class ViewModel
{
    private DataModel dm = new DataModel();
    public string ApiResult
    {
        get { return dm.apiResult; }
        set { dm.apiResult = value; }
    }
    public void GetApi()
    {
        dm.GetDataFromApi();
    }
}

最后是视图:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WPFexample" x:Class="WPFexample.MainWindow"
    DataContext="{Binding ''}"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBlock HorizontalAlignment="Left" 
        Margin="110,126,0,0" 
        TextWrapping="Wrap" 
        Text="{Binding ApiResult}"
        VerticalAlignment="Top" 
        RenderTransformOrigin="0.296,-1.239">
        <TextBlock.DataContext>
            <local:ViewModel/>
        </TextBlock.DataContext>
    </TextBlock>
</Grid>
</Window>

事实上,我不知道如何实现这一点,因为我的"apiResult"总是初始值"null",我希望它从METHODGetDataFromApi中获得结果

我如何才能在MVVM中完成所有这些工作,并实现一些接口。

我看了各种教程,但似乎无法理解,因为它们从一开始就有所欠缺,或者我不太理解其中的逻辑。。。

还将此推送给GIT:https://github.com/lklancir/WPFexample/tree/master/WPFexample/WPFexample

希望你能给我指明正确的方向。。。

如果真的调用了GetDataFromApi,它对我有效。将此代码添加到DataModel.cs,gui显示"SOME RESULT FROM WEB API"

 public DataModel()
 {
    Task.Factory.StartNew( () => this.GetDataFromApi() );
 }

但这是一个时间问题。如果在任务中添加睡眠,它将不再工作,因为没有任何内容传播属性的更改。您应该实现INotifyPropertyChanged或使用DependencyProperty。

最新更新