MVVM教程(三):第二章中示例中类的源码

MVVM教程(三):第二章中示例中类的源码,第1张

概述在第二章中我们有讲到有DesignHelper类,下面是该类的源码: using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Windows; namespace MvvmTu


在第二章中我们有讲到有DesignHelper类,下面是该类的源码:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.windows;

namespace MvvmTutorial.Infrastructure
{
public static class DesignHelper
{
#region FIElds

private static bool? _isInDesignmode;
private static Readonly Random Rand = new Random(GuID.NewGuID().GetHashCode());

#endregion // FIElds

#region PropertIEs

/// <summary >
/// Gets a value indicating whether the control is in design mode
/// (running in Blend or Visual Studio).
/// </summary >
[SuppressMessage(
"Microsoft.Security",
"CA2122:DonotindirectlyExposeMethodsWithlinkDemands",
Justification = "The security risk here is neglectible.")]
public static bool IsInDesignmode
{
get
{
if (!_isInDesignmode.HasValue)
{
#if SILVERliGHT
_isInDesignmode = DesignerPropertIEs.IsInDesignTool;
#else
#if WIN8
_isInDesignmode = windows.ApplicationModel.Designmode.DesignmodeEnabled;
#else
var prop = DesignerPropertIEs.IsInDesignmodeProperty;
_isInDesignmode
= (bool)DependencyPropertyDescriptor
 .FromProperty(prop,typeof(FrameworkElement))
 .Metadata.DefaultValue;

// Just to be sure
if (!_isInDesignmode.Value
&& Process.GetCurrentProcess().Processname.StartsWith("devenv",StringComparison.Ordinal))
{
_isInDesignmode = true;
}
#endif
#endif
}

return _isInDesignmode.Value;
}
}

#endregion // PropertIEs

#region Public Methods

/// <summary >
/// Gets a random string,given its minimum length and maximum length
/// </summary >
public static string GetRandomString(int minLen = 15,int maxLen = 50)
{
StringBuilder builder = new StringBuilder();
int length = Rand.Next(minLen,maxLen);
char ch;
for (int i = 0; i < length; i++)
{
ch = Convert.tochar(Convert.ToInt32(Math.Floor(26 * Rand.NextDouble() + 65)));
builder.Append(ch);
}

return builder.ToString().Tolower();
}

public static string GetRandomNumericString(int minLen = 15,int maxLen = 25)
{
StringBuilder builder = new StringBuilder();
int length = Rand.Next(minLen,maxLen);
for (int i = 0; i < length; i++)
{
builder.Append(Rand.Next(0,10).ToString());
}

return builder.ToString().Tolower();
}

#endregion // Public Methods
}
}

注意IsInDesignmode属性:这是我剽窃Mvvmlight的代码。它的作用在于调用它,你可以知道当前你是处于开发视图下还是runtime环境下,什么意思呢,等会儿再解释。还有一个new Contact().GeneraterandomData(),这个GeneraterandomData其实来自于一个Helper类:在Models下添加ModelHelper:

using MvvmTutorial.Infrastructure;

namespace MvvmTutorial.Models
{
public static class ModelHelper
{
public static Contact GeneraterandomData(this Contact target)
{
target.name = DesignHelper.GetRandomString(5,15);
target.PhoneNumber = DesignHelper.GetRandomNumericString(8,12);
return target;
}
}
}

这个应该很容易理解,就是给一个Contact的属性添加一些随机的数据而已,这样便于我们设计和测试。有了ContactMasterviewmodel,我们必然需要ContactMasterVIEw,于是在VIEws下添加ContactMasterVIEw,其XAML代码如下:

<UserControl x:Class="MvvmTutorial.VIEws.ContactMasterVIEw"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 xmlns:vm="clr-namespace:MvvmTutorial.viewmodels"
 mc:Ignorable="d" d:DataContext="{Binding Source={StaticResource DesignContext}}"
 d:DesignHeight="300" d:DesignWIDth="300" >
<UserControl.Resources >
<vm:ContactMasterviewmodel x:Key="DesignContext"/ >
</UserControl.Resources >
<GrID >
<ListVIEw ItemsSource="{Binding Items,Mode=OneWay}" >
<ListVIEw.VIEw >
<GrIDVIEw >
<GrIDVIEwColumn header="name" WIDth="200" >
<GrIDVIEwColumn.CellTemplate >
<DataTemplate >
<TextBlock Text="{Binding name,Mode=OneWay}" VerticalAlignment="Center"/ >
</DataTemplate >
</GrIDVIEwColumn.CellTemplate >
</GrIDVIEwColumn >

<GrIDVIEwColumn header="Phone" WIDth="150" >
<GrIDVIEwColumn.CellTemplate >
<DataTemplate >
<TextBlock Text="{Binding PhoneNumber,Mode=OneWay}" VerticalAlignment="Center"/ >
</DataTemplate >
</GrIDVIEwColumn.CellTemplate >
</GrIDVIEwColumn >
</GrIDVIEw >
</ListVIEw.VIEw >
</ListVIEw >
</GrID >
</UserControl >

请注意d:DataContext="{Binding Source={StaticResource DesignContext}}"这里,我们给VIEw绑上来一个DataContext,然而这只是开发视图环境下的DataContext而已。很多时候,当你做完VIEw以后,你希望直接可以在开发视图中看到结果,这样一来你便不需要不断编译,运行,你可以很快获得修改VIEw以后的视觉反馈(我承认我这里的中文讲话水平真的不高)。然而,还记得之前的DesignHelper.IsInDesignmode吗?它可以决定你当前是在运行程序,还是在开发视图下,如果在开发视图下,我们就给ContactMasterviewmodel.Items中添加一些随机数据,如果不是开发视图,我们才真正的要从数据层返回一些真实数据(不在本章介绍数据层)。

现在还缺什么呢?Shellviewmodel:在viewmodels下添加Shellviewmodel:

using MvvmTutorial.Infrastructure;

namespace MvvmTutorial.viewmodels
{
public class Shellviewmodel : ObservableObject
{
#region FIElds

ContactMasterviewmodel _contactMaster;

#endregion // FIElds

#region PropertIEs

public ContactMasterviewmodel ContactMaster
{
get
{
if (_contactMaster == null)
{
_contactMaster = new ContactMasterviewmodel();
}
return _contactMaster;
}
}

#endregion // PropertIEs
}
}

将ShellVIEw.xaml修改如下:

<Window x:Class="MvvmTutorial.VIEws.ShellVIEw"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vIEw="clr-namespace:MvvmTutorial.VIEws" windowstartupLocation="CenterScreen"
title="Contact Book" Height="600" WIDth="800" >
<GrID >
<vIEw:ContactMasterVIEw DataContext="{Binding ContactMaster}"/ >
</GrID >
</Window >

这里应该很好理解,我们将ContactMasterVIEw放到ShellVIEw中,并为其指定了DataContext。那么ShellVIEw的DataContext从哪里来呢?再次,为了简化教程,我们用一种比较天真直接的办法:修改该App.xaml.cs如下:

using System.windows;
using MvvmTutorial.viewmodels;
using MvvmTutorial.VIEws;

namespace MvvmTutorial
{
/// <summary >
/// Interaction logic for App.xaml
/// </summary >
public partial class App : Application
{
protected overrIDe voID OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var shell = new ShellVIEw();
var shellviewmodel = new Shellviewmodel();
shell.DataContext = shellviewmodel;
shell.Show();
}
}
}


现在按F5,运行程序,顺利的话,你应该可以看到一些随机数据显示在界面上。好了大体就先讲到这里。其实大家可以看到,我并没有什么奇思妙想,基本上就是一路“剽窃”各路高手的代码,然后自己拼凑了个小例子而已。编程总是有一些很固定的东西,而且这么多年来,全世界的编程高手,专家,都已经写出来许多拿来即用的东西,我们需要做的是掌握好基础,多读书,多关注新知识,然后“拿来主义”,让这些好用的工具为我们服务。

本文来源于:http://www.lmwlove.com/ac/ID798

总结

以上是内存溢出为你收集整理的MVVM教程(三):第二章中示例中类的源码全部内容,希望文章能够帮你解决MVVM教程(三):第二章中示例中类的源码所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1066317.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-26
下一篇2022-05-26

发表评论

登录后才能评论

评论列表(0条)

    保存